👨‍🚀 Rust Traits

= interfaces/abstract base classes in 🦀 Rust

Types

  • 👨‍🚀 Rust Trait Derivation
  • <T: Trait> -> Type T, which implements Trait “Trait”
    • multiple traits: <T: Trait1 + Trait 2>
  • as trait object: dyn Trait
    • -> implement Trait T, dynamic size

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);
}