O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

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

Ownership

When you use the let keyword, you create a temporary variable binding. Those bindings will own the things they bind. When the binding goes out of scope, the binding itself and whatever it points to gets freed. Going out of scope happens when a block ends: when a { gets closed by a }.

Here's an example:

// blocks.rs fn main() {     let level_0_str = String::from("foo");     {          let level_1_number = 9;         {             let level_2_vector = vec![1, 2, 3];         } // level_2_vector goes out of scope here         {             let level_2_number = 9;         } // level_2_number goes out of scope here     } // level_1_number goes out of scope here } // level_0_str goes out of scope here 

No surprises there, certainly. Each let binding gets allocated in the stack, and the non-primitive ...

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