怎么理解Rust Borrow Rule?

Here’s the rules about borrowing in Rust:

First, any borrow must last for a smaller scope than the owner. Second, you may have one or the other of these two kinds of borrows, but not both at the same time:

  • 0 to N references (&T) to a resource.
  • exactly one mutable reference(&mut T)

You may notice that this is very similar, though not exactly the same as, to the definition of a data race:

There is a ‘data race’ when two or more pointers access the same
memory location at the same time, where at least one of them is
writing, and the operations are not synchronized.

With references, you may have as many as you’d like, since none of them are writing. If you are writing, you need two or more pointers to the same memory, and you can only have one &mut at a time. This is how Rust prevents data races at compile time: we’ll get errors if we break the rules.

With this in mind, let’s consider our example again.

这段话到底是什么意思?

阅读 3.6k
2 个回答
  1. 0 to N references (&T) to a resource.
    一个引用(可变或者不可变的)可以有0或任意多个不可变引用(&T),就像这样

let a = Box::new(10);
// 或者
// let mut a = Box::new(10);
let b = &a;
let C = &a;
.......
  1. exactly one mutable reference(&mut T)
    只能存在一个可变引用

let mut x = 5;
let y = &mut x;
let z = &mut x;

就会报错:

main.rs:4:18: 4:19 error: cannot borrow x as mutable more than once at a time

对于一个变量,不能存在多个&mut引用。
目的就是为了避免并发时的数据竞争,但有一点需要注意:

let mut a = Box::new(10);
let b = &a;
let c = &mut a;

就会报如下错误

error: cannot borrow a as mutable because it is also borrowed as immutable

&T和&mut T是不能同时使用的, 无论先后顺序,下面的代码一样是错的:

let mut a = Box::new(10);
let b = &mut a;
let c = &a;

编译器就是依靠这样的机制在编译期发现很多问题,避免运行时出错。

以前的一篇文章


写的有点匆忙,有问题再问吧

这段话是关于在Rust语言中借用(borrowing)的规则的解释和比较。以下是对该段话的理解:

首先,任何借用必须在所有权(owner)的作用域之内。其次,你可以有以下两种借用中的一种,但不能同时拥有两种类型的借用:

0到N个对资源的引用(&T)。
正好一个可变引用(&mut T)。
你可能会注意到,这与“数据竞争”(data race)的定义非常相似,尽管不完全相同:

当两个或多个指针同时访问同一内存位置时,并且其中至少一个指针在写入,而操作没有进行同步时,就会发生“数据竞争”。

对于引用来说,你可以拥有任意多个,因为它们都是只读的。但如果要进行写入操作,你需要两个或更多指向同一内存的指针,并且一次只能有一个可变引用(&mut)。这就是Rust在编译时如何防止数据竞争的方式:如果违反了这些规则,我们将会得到错误提示。

基于这个理解,让我们再考虑一下这个例子。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏