Skip to Content
Programming Rust, 2nd Edition
book

Programming Rust, 2nd Edition

by Jim Blandy, Jason Orendorff, Leonora F. S. Tindall
June 2021
Intermediate to advanced
738 pages
18h 47m
English
O'Reilly Media, Inc.
Content preview from Programming Rust, 2nd Edition

Chapter 4. Ownership and Moves

When it comes to managing memory, there are two characteristics we’d like from our programing languages:

  • We ʼ d like memory to be freed promptly, at a time of our choosing. This gives us control over the program’s memory consumption.

  • We never want to use a pointer to an object after it’s been freed. This would be undefined behavior, leading to crashes and security holes.

But these seem to be mutually exclusive: freeing a value while pointers exist to it necessarily leaves those pointers dangling. Almost all major programming languages fall into one of two camps, depending on which of the two qualities they give up on:

  • The “Safety First” camp uses garbage collection to manage memory, automatically freeing objects when all reachable pointers to them are gone. This eliminates dangling pointers by simply keeping the objects around until there are no pointers to them left to dangle. Almost all modern languages fall in this camp, from Python, JavaScript, and Ruby to Java, C#, and Haskell.

    But relying on garbage collection means relinquishing control over exactly when objects get freed to the collector. In general, garbage collectors are surprising beasts, and understanding why memory wasn’t freed when you expected can be a challenge.

  • The “Control First” camp leaves you in charge of freeing memory. Your program’s memory consumption is entirely in your hands, but avoiding dangling pointers also becomes entirely your concern. C and C++ are the only ...

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, 2nd Edition

The Rust Programming Language, 2nd Edition

Steve Klabnik, Carol Nichols

Publisher Resources

ISBN: 9781492052586Errata PageSupplemental Content