The Copy trait

The code for this section can be found in 08/copyint and 08/copyf32.

Rust does have a way to create a copy of the original: the Copy trait (traits are covered in Chapter 10, Creating your own Crate) and all primitives implement Copy. If we have something along the lines of let varone = 1i32; or let vartwo = varone;, then i32 is a primitive type and the vartwo variable will contain a copy of varone. Both will have their own allocations on the stack, rather than vartwo pointing to varone. Ownership will not be changed; the value is duplicated and bound to the new variable.

The code for this section can be found in the 08/copyint and 08/copyf32 folders in the supporting code bundle provided for this book.

Therefore, we can write the code as follows:

fn do_something(number: i32) -> i32  
{ 
    number + 32 
} 
 
fn main()  
{ 
    let num = 10i32;  
    let numtwo = do_something(num);  
    println!("num is: {}", num); 
    println!("numtwo is : {}", numtwo); 
} 

The preceding code will give the following output when compiled (numone is an i32 value, which is a primitive, so it makes a copy of itself when passed to do_something with an i32 being returned into numtwo):

The copyf32 example shows the same Copy trait in action but for an f32 primitive.

There must be a way around this.

In a way, we've seen an answer already in many examples used throughout this book—we hand the ownership back; however, as the following code block shows, it can get a bit messy:

fn sumprod(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) 
{ 
    let sum = v1.iter().fold(0i32, |a, &b| a + b); 
    let product = v2.iter().fold(1i32, |a, &b| a * b); 
    return (v1, v2, sum + product); // return ownership 
} 
 
fn main()  
{ 
    let vecone = vec![2,3,5]; 
    let vectwo = vec![3,5];  
    let (vecone, vectwo, ans) = sumprod(vecone, vectwo); // pass ownership  
    println!("ans = {}", ans); 
} 

The preceding code will give the following output:

The code for this section can be found in the Chapter8/handback folder in the supporting code bundle provided for this book.

Thankfully, Rust does provide a neater way to pass ownership around. Instead of giving ownership, we can borrow ownership.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset