Each value in Rust has a variable that’s called its owner. (Rust中每一个变量都有一个所有者。)
There can only be one owner at a time.(在任一时刻,所有者有且仅有一个。)
When the owner goes out of scope, the value will be dropped.(当所有者离开其作用域后,它所拥有的数据会被释放。)
所有权相关编译错误
错误1
代码段1:
1 2 3
let s1 = String::from("hello"); let s2 = s1; println!("{}, world!", s1);
编译结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Compiling ownership v0.1.0 (file:///projects/ownership) error[E0382]: borrow of moved value: `s1` --> src/main.rs:5:28 | 2 | let s1 = String::from("hello"); | -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait 3 | let s2 = s1; | -- value moved here 4 | 5 | println!("{}, world!", s1); | ^^ value borrowed here after move
error: aborting due to previous error
For more information about this error, try `rustc --explain E0382`. error: could not compile `ownership`
解析:String的所有权从s1转移到s2后,不能再使用s1访问数据。否则违反原则2。
然而,对于下面这段代码,似乎产生了与代码段1矛盾的编译结果。
代码段2:
1 2 3 4 5
fnmain() { let u1:u32 = 20; let u2 = u1; println!("{}, world!", u1); }
$ cargo build Compiling hello v0.1.0 (/home/spencer/share/my_code/rust_prj/hello) error[E0382]: borrow of moved value: `s` --> src/main.rs:9:20 | 7 | let s = String::from("hello"); | - move occurs because `s` has type `String`, which does not implement the `Copy` trait 8 | print_string(s); | - value moved here 9 | println!("{}", s); | ^ value borrowed here after move