๐จโ๐ 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>
- multiple traits:
- 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);
}