Rust has a lot of traits, some of which seem really similar to each other on the surface.
To help remember this better, here’s a cheatsheet on traits with good explanations that I’ve encountered so far.
Auto Traits
Trait | Description |
---|---|
Sized | Has a known, fixed size at compile time. |
Send | |
Sync | |
Unpin | See below |
Conversion Traits
Trait | Conversion | Mnemonic |
---|---|---|
AsRef<T> | &outer → &inner | ”I’m able to produce a reference to type T ” |
Deref<T> 1 | &outer → &inner (implicit) | “Inherit” / Expose all methods from T |
Borrow<T> 2 | outer → &inner | ”I’m identical to my underlying type for all practical purposes” |
Iteration Traits
Trait | Description |
---|---|
Stream | An async iterator |
Pinning
Trait | Description |
---|---|
[[Pinning#^e0017a|Unpin ]] (auto; marker) | Such types do not have address-sensitive invariances. Pin has no effect on such types. e.g. Pin<Box<T>> where T: Unpin is equivalent to Box<T> where T: Unpin |
PhantomPinned (marker) | To convert a(n otherwise Unpin ) struct to !Unpin . This allows such structs to obey pinning invariances of Pin . |
Footnotes
-
With great power comes great responsibility. “Inherit”-ing all methods exposes the type’s public interface, leading a few issues—(1) maintenance burden, (2) inherited methods that make no sense, (3) overlapping implementations between new and inherited methods with the same name. ↩
-
Considered to be “unofficially unsafe”. I don’t fully understand the nuance yet, however. ↩