读 Rust入坑指南:核心概念 之测试,因该文中涉及一些代码不知道是什么效果,所以就做了如下的测试:
Ownership的移动 — 在String之间转移
let s1 = String::from("hello");
let s2 = s1;
println!("s1: {}", s1);
执行上面的代码会报如下错误:
warning: unused variable: `s2`
--> src\main.rs:7:7
|
7 | let s2 = s1;
| ^^ help: if this is intentional, prefix it with an underscore: `_s2`
|
= note: `#[warn(unused_variables)]` on by default
error[E0382]: borrow of moved value: `s1`
--> src\main.rs:8:22
|
6 | let s1 = String::from("hello");
| -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
7 | let s2 = s1;
| -- value moved here
8 | println!("s1: {}", s1);
| ^^ value borrowed here after move
error: aborting due to previous error; 1 warning emitted
For more information about this error, try `rustc --explain E0382`.
error: could not compile `hello_cargo`
To learn more, run the command again with --verbose.