Expand description
A common interface for a group of types.
Atrait is like an interface that data types can implement. When a typeimplements a trait it can be treated abstractly as that trait using genericsor trait objects.
Traits can be made up of three varieties of associated items:
- functions and methods
- types
- constants
Traits may also contain additional type parameters. Those type parametersor the trait itself can be constrained by other traits.
Traits can serve as markers or carry other logical semantics thataren’t expressed through their items. When a type implements thattrait it is promising to uphold its contract.Send andSync are twosuch marker traits present in the standard library.
See theReference for a lot more information on traits.
§Examples
Traits are declared using thetrait keyword. Types can implement themusingimplTraitforType:
traitZero {constZERO:Self;fnis_zero(&self) -> bool;}implZerofori32 {constZERO:Self=0;fnis_zero(&self) -> bool {*self==Self::ZERO }}assert_eq!(i32::ZERO,0);assert!(i32::ZERO.is_zero());assert!(!4.is_zero());With an associated type:
Traits can be generic, with constraints or without:
Traits can build upon the requirements of other traits. In the examplebelowIterator is asupertrait andThreeIterator is asubtrait:
Traits can be used in functions, as parameters:
fndebug_iter<I: Iterator>(it: I)whereI::Item: std::fmt::Debug {foreleminit {println!("{elem:#?}"); }}// u8_len_1, u8_len_2 and u8_len_3 are equivalentfnu8_len_1(val:implInto<Vec<u8>>) -> usize { val.into().len()}fnu8_len_2<T: Into<Vec<u8>>>(val: T) -> usize { val.into().len()}fnu8_len_3<T>(val: T) -> usizewhereT: Into<Vec<u8>>,{ val.into().len()}Or as return types:
The use of theimpl keyword in this position allows the function writerto hide the concrete type as an implementation detail which can changewithout breaking user’s code.
§Trait objects
Atrait object is an opaque value of another type that implements a set oftraits. A trait object implements all specified traits as well as theirsupertraits (if any).
The syntax is the following:dyn BaseTrait + AutoTrait1 + ... AutoTraitN.Only oneBaseTrait can be used so this will not compile:
Neither will this, which is a syntax error:
On the other hand, this is correct:
TheReference has more information about trait objects,their limitations and the differences between editions.
§Unsafe traits
Some traits may be unsafe to implement. Using theunsafe keyword infront of the trait’s declaration is used to mark this:
§Differences between the 2015 and 2018 editions
In the 2015 edition the parameters pattern was not needed for traits:
This behavior is no longer valid in edition 2018.