kakts-log

programming について調べたことを整理していきます

Rust: Error for copying String allocated memory to new variable.

When I write Rust code as below, it occurs error. I tried to print two same String by copying memory.

fn main() {
    let s1 = String::from("Hello");
    let s2 = s1;
    println!("{}, {}", s1, s2);
}
error[E0382]: use of moved value: `s1`
  --> src/main.rs:14:24
   |
13 |     let s2 = s1;
   |         -- value moved here
14 |     println!("{}, {}", s1, s2);
   |                        ^^ value used here after move
   |
   = note: move occurs because `s1` has type `std::string::String`, which does not implement the `Copy` trait

error: aborting due to previous error

error: Could not compile `owner`.

The reason of this is arisen from Rust's memory management. In The Rust code, String pointer is assigned to two variables s1, s2.
If s2 is tried tobe copied allocated memory value of s1, s1 variable goes out of scope, it no longer be valid.
This is one of the mechanism of Rust's memory management called move .

So in this case, s1 is already moved to s2, it is invalid to use s1 in println!() .