让我们尝试编译这段代码:
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/