๐Ÿ‘จโ€๐Ÿš€ Rust Traits

= interfaces/abstract base classes in ๐Ÿฆ€ Rust

Types

When to use which?

  • Trait generics:
    • speed
    • not every trait can support trait objects
    • easy to bound generic type parameter with several traits at once
  • Trait objects:
    • simple types, usage like Java interface
    • collection of values of myixed types, all together

Usage

  • Implementing a trait: impl TraitName for Type
  • Subtype: trait SubTrait : SuperTryit {...}

๐Ÿ“– Example:

trait Talker {
	fn talk(&mut self) -> String;
	fn listen(&mut self, text: String);
}