借用,借用不会引起所有权转移,借用是指对一块内存空间的引用。
fn main() {
let a1 = String::from("hello");
let a2 = &a1;
println!("a1 is: {}", a1);
println!("a2 is: {}", a2);
}
所有权转移
fn main() {
let b1 = String::from("rust good good");
let b2 = b1;
println!("b1 is: {}", b1);
println!("b2 is: {}", b2);
}
这时b1的所有权转移给了b2,再来打印b1时,编译出错,因为这时b1不能再使用了。
记住:Rust中的每个值都必定有一个唯一控制者,即,所有者。
error[E0382]: borrow of moved value: `b1`
--> src/main.rs:15:27
|
13 | let b1 = String::from("rust good good");
| -- move occurs because `b1` has type `String`, which does not implement the `Copy` trait
14 | let b2 = b1;
| -- value moved here
15 | println!("b1 is: {}", b1);
| ^^ value borrowed here after move
刚入rust,很容易受C中的&和java中变量之间互相赋值思维的影响:(
网友评论