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.
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:
Thankfully, Rust does provide a neater way to pass ownership around. Instead of giving ownership, we can borrow ownership.