Chapter 5. References
Libraries cannot provide new inabilities.
Mark Miller
In the last chapter, we discussed the types Box<T>, Vec<T>, and String, all of which contain a pointer to some data in the heap, which they own. A value’s owner is responsible for cleaning up after it: dropping a Box<T> drops the T as well. Rust also has non-owning pointer types called references, which have no effect on their referents’ lifetimes. A reference points to a value and grants read or read-write access to it, usually temporary access. It does not grant ownership. Rust refers to creating a reference as borrowing: what you have borrowed, you must eventually return to its owner.
The references themselves are nothing special—under the hood, they’re just addresses. But the rules that keep them safe are novel to Rust; outside of research languages, you won’t have seen anything like them before. And although these rules are the part of Rust that requires the most effort to master, the breadth of classic, absolutely ...
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.
Read now
Unlock full access