What is the difference between passing a value to a function by reference and passing it "by Box":
fn main() {
let mut stack_a = 3;
let mut heap_a = Box::new(3);
foo(&mut stack_a);
println!("{}", stack_a);
let r = foo2(&mut stack_a);
// compile error if the next line is uncommented
// println!("{}", stack_a);
bar(heap_a);
// compile error if the next line is uncommented
// println!("{}", heap_a);
}
fn foo(x: &mut i32) {
*x = 5;
}
fn foo2(x: &mut i32) -> &mut i32 {
*x = 5;
x
}
fn bar(mut x: Box<i32>) {
*x = 5;
}
Why is heap_a
moved into the function, but stack_a
is not (stack_a
is still available in the println!
statement after the foo()
call)?
The error when uncommenting println!("{}", stack_a);
:
error[E0502]: cannot borrow `stack_a` as immutable because it is also borrowed as mutable
--> src/main.rs:10:20
|
8 | let r = foo2(&mut stack_a);
| ------- mutable borrow occurs here
9 | // compile error if the next line is uncommented
10 | println!("{}", stack_a);
| ^^^^^^^ immutable borrow occurs here
...
15 | }
| - mutable borrow ends here
I think this error can be explained by referring to lifetimes. In the case of foo
, stack_a
(in the main
function) is moved to function foo
, but the compiler finds that the lifetime of the argument of the function foo
, x: &mut i32
, ends at end of foo
. Hence, it lets us use the variable stack_a
in the main
function after foo
returns. In the case of foo2
, stack_a
is also moved to the function, but we also return it.
Why doesn't the lifetime of heap_a
end at end of bar
?