rust - 为什么有时可以从不可变数组中借用 &mut 引用?

标签 rust

让我们尝试编译这段代码:

trait Bar {
    fn bar(&mut self);
}

fn foo(a1: &mut Bar, j: usize) {
    let a = [a1];
    a[0].bar(); //compilation ok
    a[j % 2].bar();
}

fn main() {}

编译错误:

error[E0596]: cannot borrow immutable local variable `a` as mutable
 --> src/main.rs:8:5
  |
6 |     let a = [a1];
  |         - consider changing this to `mut a`
7 |     a[0].bar(); //compilation ok
8 |     a[j % 2].bar();
  |     ^ cannot borrow mutably

为什么 a[0].bar() 可以,但是 a[j % 2].bar() 失败了?是编译器错误吗?

最佳答案

Is it a compiler bug?

Yes .它在 Rust 1.25.0-nightly (2018-01-09 61452e506f0c88861cccaeea4ced3419bdb3cbe0) 中由 PR 47167 修复

简而言之,有两种执行索引的方式,称为“内置索引”和“重载索引”。正如您可能从名称中猜到的那样,一个是编译器固有的,另一个是用户可自定义的。

在这种情况下,重载索引正在执行不需要的数组借用,从而触发警告。您可以通过简化类型推断的编译器工作来解决这个问题:

fn foo(a1: &mut Bar, j: usize) {
    let a = [a1];
    let x: usize = j % 2;
    a[x].bar();
}

通过显式声明索引是 usize,代码现在将使用内置索引。

关于rust - 为什么有时可以从不可变数组中借用 &mut 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47375184/

相关文章:

string - "Borrowed value does not live long enough", 在循环中使用时丢弃

rust - 如何通过适配器在一行中重复或连接两个切片 n 次?

iterator - 如何遍历向后范围?

rust - Rust `Stream` 如何理解何时调用 `poll_next` ?

multithreading - 生成线程时无法共享Arc变量

c++ - rust-bindgen 绑定(bind)引发 SIGSEGV

postgresql - Rust:如何将SocketAddr转换为IpNetwork?

rust - 我不断收到 ParseIntError { kind : InvalidDigit } in my Rust program and I have no idea why

mongodb - 无法连接到 rust 的MongoDB Atlas数据库

linux - 使用 Rust DBUS 库时不满足 trait bound `dbus::arg::Get`