fn main() {
let a = vec![2, 4, 8];
{
let b = a; // move value of 'a' to 'b'
println!("b : {:?} ", b); // prints 'b'
}
// println!("{}", b) // Error, b is out of scope (dropped)
println!("a : {:?} ", a); // Error; borrow of moved value <<<<<< WHY CAN'T DO THIS? The ownership didn't back to a since b is dropped?
}
If it's allowed it would be an use-after-free bug. The type of the variable b
is Vec<i32>
so it will drop its contents and buffer when it goes out of its scope.
It's borrowing which ends automatically when it goes out of scope. Ownership never come back implicitly.
Ownership never ”goes back” automatically. When b is dropped, whatever resources it owns are freed and can’t even in principle go back to a previous owner, if any. If you give me a lollipop, as a gift, and then I eat it, you can’t expect to get it back.
What you need instead is to borrow, ie. to use a reference. Borrowing is temporary and the original gets to use a borrowed value again once the borrow goes out of scope.
Owned values can only exist in one place at a time. The vec can't be in both a
and b
.
It works if you move the value back to a
explicitly:
fn main() {
let mut a = vec![2, 4, 8];
{
let b = a; // move value of 'a' to 'b'
println!("b : {:?} ", b); // prints 'b'
a = b; // give it back
}
println!("a : {:?} ", a);
}
Thank you very much for the answer. I got it! Perfect example. For me, a=b and a=& b would have the same behavior, but I understood that is not the same.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.