如何解决无法通过索引访问向量中的可变引用
我需要遍历可变引用的向量;这是简化的复制品:
trait Ticking {
fn tick(&mut self);
}
trait Fish {}
struct World<'a> {
fish: Vec<&'a mut dyn Fish>,}
impl<'a> Ticking for World<'a> {
fn tick(&mut self) {
let _fish: &mut dyn Fish = self.fish[0];
//let _fish: &mut dyn Fish = self.fish.get_mut(0).expect("expected value");
}
}
struct Guppy<'a> {
n_ref: &'a usize,}
impl<'a> Fish for Guppy<'a> {}
fn main() {
let mut guppy: Guppy = Guppy { n_ref: &5 };
let _world: World = World {
fish: vec![&mut guppy],};
}
我收到以下错误:
error[E0596]: cannot borrow data in an index of `std::vec::Vec<&mut dyn Fish>` as mutable
--> src/main.rs:15:36
|
15 | let _fish: &mut dyn Fish = self.fish[0];
| ^^^^^^^^^^^^ cannot borrow as mutable
|
= help: trait `IndexMut` is required to modify indexed content,but it is not implemented for `std::vec::Vec<&mut dyn Fish>`
我尝试直接致电get_mut
并收到终身绑定错误:
error[E0277]: the trait bound `&'a mut (dyn Fish + 'a): Fish` is not satisfied
--> src/main.rs:13:36
|
13 | let _fish: &mut dyn Fish = self.fish.get_mut(0).expect("expected value");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Fish` is not implemented for `&'a mut (dyn Fish + 'a)`
|
= note: required for the cast to the object type `dyn Fish`
编译器的说明无助于确定根本原因。
解决方法
您(1)使用错误的语法进行索引编制,并且(2)您的类型不匹配:
let _fish: &mut &mut dyn Fish = &mut self.fish[0];
// ^^^^ 2 ^^^^ 1
无论如何,这里没有理由要使用显式类型:
let _fish = &mut self.fish[0];
另请参阅:
- How can I use `index_mut` to get a mutable reference?
- What is the return type of the indexing operation?
在这里,编译器错误地选择了Index
特征而不是IndexMut
特征,并给出了错误的错误消息。我filed a bug表示这种行为,但事实证明,Rust的beta版和夜间版本实际上已修复了该问题。 Beta版将于下周稳定发布,因此将来您的代码将可以使用。
同时,有几种方法可以使代码在当前稳定版本和旧版本的Rust上运行。最简洁的方法是通过仅在分配的右侧添加IndexMut
来迫使编译器选择&mut
:
let _fish: &mut dyn Fish = &mut self.fish[0];
现在右侧的类型为&mut &mut dyn Fish
,因此编译器将应用反引用强制。或者,您可以显式取消引用右侧的*&mut self.fish[0]
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。