根据铁 rust 书,我们不能同时使用变量作为可变和不可变的引用.

但出于某种原因,当我try 对u32类型执行此操作时,它不会抛出任何错误.

fn main() {
    let mut num = 69;
    do_something(&mut num); // no error
    dont_do_anything(&num); // no error
    println!("{}", num);
}

fn dont_do_anything(num: &u32) {
    println!("{}", num);
}

fn do_something(num: &mut u32)  {
    *num += 1;
}

我是不是漏掉了什么?

推荐答案

你不是同时超过他们,你是一个接一个地超过他们.

fn main() {
    let mut num = 69;
    // at the following line you start to borrow num mutably
    do_something(&mut num);
    // but the mutable borrow is only used in the line above

    // at the following line you start a shared borrow of num
    dont_do_anything(&num);
    // and you only use the shared borrow in the line above.

    // then you do another shared borrow for `pritnln`
    println!("{}", num);
    // which is used just in the one line again.
}

由于任何borrow 之间都不会发生重叠,因此没有违反任何borrow 规则. 现在让我们来看看一些不被允许的事情:

fn main() {
    let mut num = 69;
    // start mutably borrowing
    let mut_num = &mut num;
    // try to borrow immutably after we started a mutable borrow, but before we stopped using it
    dont_do_anything(&num);
    // use the mutable borrow here
    do_something(mut_num);
}

这段代码确实同时使用了可变和不可变的借入(我们调用dont_do_anything的那一行),因此编译器会对我们大喊大叫:

   Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `num` as immutable because it is also borrowed as mutable
 --> src/main.rs:6:22
  |
4 |     let mut_num = &mut num;
  |                   -------- mutable borrow occurs here
5 |     // try to borrow immutably after we started a mutable borrow, but before we stopped using it
6 |     dont_do_anything(&num);
  |                      ^^^^ immutable borrow occurs here
7 |     // use the mutable borrow here
8 |     do_something(mut_num);
  |                  ------- mutable borrow later used here

Rust相关问答推荐

rust 蚀生命周期 行为

是否可以使用Serde/Rust全局处理无效的JSON值?

为什么特征默认没有调整大小?

实现 Deref 的 struct 可以返回对外部数据的引用吗?

Rust:为什么 &str 不使用 Into

借来的价值生命周期 不够长,不确定为什么它仍然是借来的

面临意外的未对齐指针取消引用:地址必须是 0x8 的倍数,但为 0x__错误

Rust 为什么被视为borrow ?

如何基于常量在Rust中跳过一个测试

如何将 C++ 程序链接到 Rust 程序,然后将该 Rust 程序链接回 C++ 程序? (cpp -> rust -> cpp)

由特征键控的不同 struct 的集合

为什么不可变特征的实现可以是可变的?

如何将这些测试放在一个单独的文件中?

在线程中运行时,TCPListener(服务器)在 ip 列表中的服务器实例之前没有从客户端接受所有客户端的请求

Rust Serde 为 Option:: 创建反序列化器

你能告诉我如何在 Rust 中使用定时器吗?

从函数返回 u32 的数组/切片

如何在 nom 中构建负前瞻解析器?

为什么这个 Trait 无效?以及改用什么签名?

守卫如何影响匹配语句?