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
(theclone
method)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
Returning Types that Implement Traits
Clone
- Clone in std::clone - Rust
TheClone
trait is a trait in Rust that allows you to create a copy of an object.
Error
- Error in std::error - Rust
TheError
trait is a trait in Rust that represents the basic expectations for error values, i.e., values of typeE
inResult<T, E>
.
Errors must describe themselves through theDisplay
andDebug
traits
PartialEq
- PartialEq in std::cmp - Rust
x.eq(y)
can also be writtenx == y
, andx.ne(y)
can be writtenx != y
.a != b
if and only if!(a == b)
.
ToOwned
- ToOwned in alloc::borrow - Rust
Clone
works only for going from&T
toT
. TheToOwned
trait generalizesClone
to 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 aResult
type 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.