怎么理解Rust Borrow Rule?

发布于 2022-09-01 18:13:24 字数 1064 浏览 20 评论 0

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.

这段话到底是什么意思?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

看透却不说透 2022-09-08 18:13:24
  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;

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

以前的一篇文章


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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文