O'Reilly logo

Rust Essentials - Second Edition by Ivo Balbaert

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

Copying and moving values - The copy trait

In the code we looked at above (see Chapter 7/code/lifetimes.rs) the value of n is copied to a new location each time n is assigned via a new let binding or passed as a function argument:

let n = 42u32; 
let n2 = n; // no move, only a copy of the value n to n2 
 
life(n); // copy of the value n to m 
 
fn life(m: u32) -> u32 { 
    let o = m; // copy of the value m to o 
    o 
} 

At a certain moment in the program's execution we would have four memory locations containing the copied value 42, which we could visualize as follows:

Each value disappears (and its memory location is freed) when the lifetime of its corresponding ...

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