Chapter 13. Utility Traits
Science is nothing else than the search to discover unity in the wild variety of nature—or, more exactly, in the variety of our experience. Poetry, painting, the arts are the same search, in Coleridge’s phrase, for unity in variety.
Jacob Bronowski
Apart from operator overloading, which we covered in the previous chapter, several other built-in traits let you hook into parts of the Rust language and standard library:
You can use the
Droptrait to clean up values when they go out of scope, like destructors in C++.Smart pointer types, like
Box<T>andRc<T>, can implement theDereftrait to make the pointer reflect the methods of the wrapped value.By implementing the
From<T>andInto<T>traits, you can tell Rust how to convert a value from one type to another.
This chapter is a grab bag of useful traits from the Rust standard library. We’ll cover each of the traits shown in Table 13-1.
There are other important standard library traits as well. We’ll cover Iterator and IntoIterator in Chapter 15. The Hash trait, for computing hash codes, is covered in Chapter 16. And a pair of traits that mark thread-safe types, Send and Sync, are covered in Chapter 19.
| Trait | Description |
|---|---|
Drop
|
Destructors. Cleanup code that Rust runs automatically whenever a value is dropped. |
Sized
|
Marker trait for types with a fixed size known at compile time, as opposed to types (such as slices) that are dynamically sized. ... |