Rust: Pass-By-Value or Pass-By-Reference?
- pass-by-value means that when passing an argument to a function it gets copied into the new function so that the value in the calling function and the value in the called function are two separate values. Changes to one will not in turn result in the same change to the other.
- Pass-by-reference, on the other hand, means that when passing an argument to a function, it doesn’t copy the value but rather the argument is merely a transparent reference to the original value. This means changes to the value in the called function change the value in the calling function since they are the same value.
Rust is strictly a pass-by-value language.
This might surprise you since references play a big part in the language. However, references in Rust are first class citizens. They, themselves, are values that can be passed - by value - to a function.
Let’s take a look at some examples:
fn main() { let n_main: usize = 100; println!("n_main address: {:p}", &n_main); // -> n_main address: 0x7ffc85a69758 let inc = inc(n_main); println!("inc addr: {:p}", &inc); // -> inc addr: 0x7ffc85a697b0 println!("inc: {}", inc); // -> 101 println!("n_name: {}", n_main); // -> n_name: 100 } fn inc(n_inc: usize) -> usize { println!("n_inc address: {:p}", &n_inc); // -> n_inc address: 0x7ffc85a69638 println!("n_inc: {:?}", n_inc); // -> n_inc: 100 n_inc + 1 }
- n_main is a number allocated on the stack of the main function.
- When we pass n_main to the inc function it is copied to the stack of the inc function.
- n_main and n_inc are two separate values at two places in memory.
fn main() { let n_main: usize = 100; let n_main_ref: &usize = &n_main; println!("&n_main: {:p}, n_main_ref: {:p}", &n_main, n_main_ref ); // &n_main: 0x7ffec91507d0, n_main_ref: 0x7ffec91507d0 let inc = inc_ref(n_main_ref); println!("inc addr: {:p}", &inc); // -> inc addr: 0x7ffec9150848 println!("inc: {}", inc); // -> inc: 101 } fn inc_ref(n_inc_ref: &usize) -> usize { println!("n_inc_ref: {:p}", n_inc_ref); // -> n_inc_ref: 0x7ffec91507d0 n_inc_ref + 1 }
- the function inc_ref works the same way as inc did before just now with the value being a reference instead of a number of type usize.
- When we pass n_main_ref to inc_ref, the reference value n_main_ref (not the value that it’s pointing to) is copied to the stack of inc_ref.
- The reference is a value and it behaves with pass-by-value semantics just like the value of type usize did.
Let’s take a look at another example to drive the case home:
⭐️ the array is a fixed-size list of elements, of the same data type. Even with mut, its element count can not be changed. While A vector is kind of a re-sizable array but all elements must be in the same type.
fn main() { let array_main: [Vec<u8>; 3] = [vec![1], vec![2, 4], vec![]]; print(array_main); } fn print(array: [Vec<u8>; 3]) { for e in array.iter() { println!("{:?}", e) } } /* * output: * [1] * [2, 4] * [] */
This example is the exact same as the above examples except the underlying value we’re looking at is a fixed length array with elements that are Vecs. In the case of the print function, the array will be copied from the stack of the main function to the stack of the print function. This means that each of the three elements (the Vecs) will be copied to the new stack frame.
It’s important to be clear what “copying” means here. While logically we might think of a Vec as a growable array on the heap, in reality is is just a struct that contains three values: a length, a capacity and a pointer to the actual data on the heap. When we say the Vec is copied - we mean this struct is copied. The data on the heap, however, is not copied.
Now if Rust didn’t have the borrow checker this could present a problem. Why? Copying one of the Vecs would lead to two pointers (a.k.a. aliased pointers) to the same data on the heap. If we then “dropped” (a.k.a freed, a.k.a. deallocated, a.k.a. destroyed) one of the Vecs (and in turn free the heap allocated memory), the pointer in other Vec would now point to junk data. Luckily, the borrow checker makes it impossible to use array_main after it’s been “moved” to the print function.
Ok, now let’s look again at passing a reference by value:
fn main() { let array_main: [Vec<u8>; 3] = [vec![1], vec![2, 4], vec![]]; let array_main_ref: &[Vec<u8>] = &array_main; print(array_main_ref); } fn print(array_ref: &[Vec<u8>]) { for e in array_ref.iter() { println!("{:?}", e) } } /* * output: * [1] * [2, 4] * [] */
This example again is pass-by-value semantics. The value in question is the reference to our stack allocated array. The reference array_main_ref will be copied from main’s stack to the stack of the print function, but of course, the array itself will not be copied and will stay on the stack of the main function.