所有者可以读取数据,而另一个线程通过可变借用更改值,对吧?
这是不正确的,甚至是否涉及多个线程都没有关系。
您可以在下面的示例中亲自查看()。这是一个字符串值x
被修改,同时保留对相同值的引用y
:
let mut x = "123".to_string();
let y = &mut x;
x.push_str("456");
println!("y = {}", y);
这无法编译:
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> src/main.rs:5:5
|
3 | let y = &mut x;
| ------ first mutable borrow occurs here
4 |
5 | x.push_str("456");
| ^ second mutable borrow occurs here
6 |
7 | println!("y = {}", y);
| - first borrow later used here
当我们尝试打电话时push_str
,一个方法接收&mut self
,假设当场构建对该值的新的可变引用。自从x
已经在该范围内借用了,这是非法的。
现在,您甚至可以考虑重新分配而不是调用期望的方法&mut self
。尽管如此,机会还是很大的:
let mut x = "123".to_string();
let y = &mut x;
x = "321".to_string();
println!("y = {}", y);
error[E0506]: cannot assign to `x` because it is borrowed
--> src/main.rs:5:5
|
3 | let y = &mut x;
| ------ borrow of `x` occurs here
4 |
5 | x = "321".to_string();
| ^ assignment to borrowed `x` occurs here
6 |
7 | println!("y = {}", y);
| - borrow later used here
借用的值也不能重新分配。
总而言之,价值的所有者仍然受到无论哪种借贷的限制。如果该值是不可变地借用的,则所有者也可以具有不可变的访问权限,但该值永远不能被写给 or moved只要借款到位。
当该值被可变借用时,所有者无法对该值执行任何操作,直到该引用被删除。