A trait defines functionality a particular type has and can share with other types. We can use traits to define shared behavior in an abstract way.
Data types can implement traits. To do so, the methods making up the trait are defined for the data type. For example, the String data type implements the From<&str> trait. This allows a user to write String::from("hello").
In this way, traits are somewhat similar to Java interfaces and C++ abstract classes.
Some additional common Rust traits include:
Clone(theclonemethod)Display(which allows formatted display via{})Debug(which allows formatted display via{:?})
Because traits indicate shared behavior between data types, they are useful when writing generics.
Traits as Parameters
// with trait bound
fn compare_license_types<T: Licensed, U: Licensed>(software: T, software_two: U) -> bool
// without trait bound
fn compare_license_types(software: impl Licensed, software_two: impl Licensed) -> bool
// Multiple trait bound using +
fn some_func(item: impl SomeTrait + OtherTrait) -> bool
// or use where T: SomeTrait + OtherTraitReturning Types that Implement Traits
fn returns_summarizable() -> impl Summary {
Tweet {
username: String::from("horse_ebooks"),
content: String::from(
"of course, as you probably already know, people",
),
reply: false,
retweet: false,
}
}Clone
- Clone in std::clone - Rust
TheClonetrait is a trait in Rust that allows you to create a copy of an object.
Error
- Error in std::error - Rust
TheErrortrait is a trait in Rust that represents the basic expectations for error values, i.e., values of typeEinResult<T, E>.
Errors must describe themselves through theDisplayandDebugtraits
PartialEq
- PartialEq in std::cmp - Rust
x.eq(y)can also be writtenx == y, andx.ne(y)can be writtenx != y.a != bif and only if!(a == b).
ToOwned
- ToOwned in alloc::borrow - Rust
Cloneworks only for going from&TtoT. TheToOwnedtrait generalizesCloneto construct owned data from any borrow of a given type.
Debug
- Debug in std::fmt - Rust
Used in{:?}
From
- From in std::convert - Rust
value to value conversion
TryFrom/TryInto
- TryFrom in std::convert - Rust
this should return aResulttype instead of the target type itself.
AsRef/AsMut
- AsRef in std::convert - Rust
- AsMut in std::convert - Rust
AsRef and AsMut allow for cheap reference-to-reference conversions.