O'Reilly logo

Programming Rust by Jason Orendorff, Jim Blandy

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 Drop trait to clean up values when they go out of scope, like destructors in C++.

  • Smart pointer types, like Box<T> and Rc<T>, can implement the Deref trait to make the pointer reflect the methods of the wrapped value.

  • By implementing the From<T> and Into<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.

Table 13-1. Summary of utility traits
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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required