Move strings
- We can assign a variable that contains a "mutable string" to another variable
- But this is called a "move" as we move the ownership of the data to the new variable.
- After that we cannot use the old variable any more.
- This will be fun when would like to change one of the variables or if we pass it to a function.
- The variable "owns" the data.
- If we assign the variable to another variable, we pass (move) the ownership.
examples/ownership/move-string/src/main.rs
fn main() { let name = String::from("Foo"); println!("{name}"); let other = name; println!("{other}"); // println!("{name}"); // value borrowed here after move }
Foo Foo
error[E0382]: borrow of moved value: `name` --> examples/ownership/move_string.rs:8:15 | 2 | let name = String::from("Foo"); | ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait ... 5 | let other = name; | ---- value moved here ... 8 | println!("{name}"); // value borrowed here after move | ^^^^^^ value borrowed here after move | = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider cloning the value if the performance cost is acceptable | 5 | let other = name.clone(); | ++++++++ error: aborting due to previous error For more information about this error, try `rustc --explain E0382`.