Quick MOVE question


#1

Why does this work? -
var S got moved to var T. And var S got assigned a value…

let mut s = “A”.to_string();
let t = s;
s = “B”.to_string();
println!("{} - {}", s, t);

I expected an error saying S is owned by T - therefore cloning S in var T initialization…

Does it work because it’s a string literal (i.e. known fixed size up front)?


#2

It works because it’s the value itself that’s moved, not the variable. You can imagine the program’s state as follows:

let mut s = “A”.to_string();
// s: [String::from("A")]
let t = s;
// s: [                 ], t: [String::from("A")]
s = “B”.to_string();
// s: [String::from("B")], t: [String::from("A")]
```
PS: Use "```" fences to paste the code
```