Reputation: 19
I wrote the line of codes below:
fn main() {
let mut s = vec!["my".to_string(), "here".to_string(), "babe".to_string()];
let t = s;
s = vec!["three".to_string()];
let u = s;
}
based on my understanding of rust compiler behavior and the rules of rust ownership, after I moved the ownership of the value of s
(which is not a primitive type and doesn't implement COPY trait cause it's type of Vec) to t
in line 2, I should not be able to change the value of s
cause this variable (I mean s
) is not valid anymore! but this lines of code are valid at all. Can anyone explain why ?
I expect that to face an compiler error by run this code!
Upvotes: 1
Views: 71
Reputation: 5467
Yes, after let t = s;
the value that was in s
has been moved out. But you can simply think of s
as an uninitialized variable now. So when you assign to s
again, you are not changing the value that was moved out.
You seem to expect the borrow checker to scream at you, but you are not borrowing anything. You are moving values around that you own without ever creating a reference. Your code never creates two ways of accessing the same value, and you're never reading an uninitialized value.
Upvotes: 0
Reputation: 1295
You are correct about you cannot read s
while some scope because vec!["my", "here", "babe"]
(omitted to_string
for simplification) moved into t
and vector is not Copy
. However, in Rust, you are able to read from (or write to) s
again once if you reassign some vector to it (yes, it also can be moved out to somewhere).
Technically it is equivalent with following code, and works fine:
let mut s = vec!["my".to_string(), "here".to_string(), "babe".to_string()];
let t = s;
let s2 = vec!["three".to_string()];
let u = s2;
Upvotes: 1