I'm fresh to rust and got confused by the reference concept.
From the book I know that passing a variable to a function will change its ownership.
And shared reference is Copy
but mutable reference is not.
Based on the above, I wrote the following code and it runs ok:
fn main() {
let mut v0 = vec![1, 2, 3];
let mut_ref_v0 = &mut v0;
do_something(mut_ref_v0);// mut_ref_v0 moved into this scope
do_something(mut_ref_v0);// still alive? Why?
}
fn do_something(v: &mut Vec<i32>) {
v.push(4);
for i in v {
println!("{}", i);
}
}
As far as I know, when the variable mut_ref_v0
is passed to do_something
first time, the variable mut_ref_v0
becomes uninitialized and its ownership is transferred to the variable v
in the do_something
function.Then I use the variable mut_ref_v0
again, no errors?