Traits and Generics
Traits Are Interface Types
Define methods, fields and types that must be present in the implementation of a struct or enum
Principal mechanism for code reuse in Rust
Interact strongly with and enhance "generic" types (parametric polymorphism)
Defining A Trait
Just an interface specification
Here's a hairy version
https://play.rust-lang.org/?gist=d0087cd38ededa59f70297615c676254
Note the following:
- Trait bounds
- Associated type
- Static (default) method
- Use of Sized marker type
- Use of Self
- Clever type inference
- Implementation of our trait for standard types
Trait Bounds vs Trait Objects
Book example
https://play.rust-lang.org/?gist=8aaa8fe367b1e495c0318d777bd0e83b
A specialized version of
generic_salad.add(*v)
will be constructed, no argument need be passed, the whole thing will be inlinedNote the awkwardness of working with trait objects. This code is fairly fragile
Misc Trait Things
Traits and scope control
Subtraits
Last modified: Tuesday, 1 May 2018, 5:02 PM