Advanced traits
In this section, we'll discuss some of the advanced traits that are important to know when we are dealing with complex code bases.
Sized and ?Sized
The Sized
trait is a marker trait that represents types whose sizes are known at compile time. It is implemented for most types in Rust except for unsized types. All type parameters have an implicit trait bound of Sized
in their definition. We can also specify optional trait bounds using the ?
operator before a trait, but the ?
operator with traits only works for marker traits as the time of writing this book. It may be extended to other types in future.
Borrow and AsRef
These are special traits that carry the notion of able to construct a out of any type.
ToOwned
This trait is meant to be implemented for types that can be converted in to an owned version. For example, the &str
type has this trait implemented for String
. This means the &str
type has a method called to_owned()
on it that can convert it in to a String
type, which...