关于变量的可变引用的问题
问题
先贴代码
fn main() {
let mut s1 = String::from("hello");
let s2 = &mut s1;
println!("{}",s1);
println!("{}",s2);
}
上面代码报错
error[E0502]: cannot borrow `s1` as immutable because it is also borrowed as mutable
--> test.rs:4:19
|
3 | let s2 = &mut s1;
| ------- mutable borrow occurs here
4 | println!("{}",s1);
| ^^ immutable borrow occurs here
5 | println!("{}",s2);
| -- mutable borrow later used here
然后代码改成下面这样就可以运行了
fn main() {
let mut s1 = String::from("hello");
let s2 = &mut s1;
println!("{}",s2);
println!("{}",s1);
}
猜想
1.在s2引用s1之后会获取值的使用权,s1会失去值的使用权;
2.在编译阶段编译器分析使用权归哪个变量;
3.如问题代码:在s2释放使用权之前访问s1,所以报错;
4.如更正代码:编译器在访问s1时判断之后没有再访问s2,就把s2的使用权释放,s1获得使用权,所以不报错;
5.可变引用可以等价于所有权的两次移动。
推荐文章: