Skip to Content
Programming Rust
book

Programming Rust

by Jim Blandy, Jason Orendorff
December 2017
Intermediate to advanced content levelIntermediate to advanced
619 pages
15h 11m
English
O'Reilly Media, Inc.
Content preview from Programming Rust

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. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Rust Programming Language

The Rust Programming Language

Steve Klabnik, Carol Nichols
Programming Rust, 2nd Edition

Programming Rust, 2nd Edition

Jim Blandy, Jason Orendorff, Leonora F. S. Tindall
The Rust Programming Language, 2nd Edition

The Rust Programming Language, 2nd Edition

Steve Klabnik, Carol Nichols

Publisher Resources

ISBN: 9781491927274Errata PageSupplemental Content