结构内部的共享所有权(mutable_borrow_reservation_conflict警告)



以下代码编译并运行,但会发出mutable_borrow_reservation_conflict警告。

我的目标是让字段all_ops拥有一组Op的实现(只读(,其中每个Op都可以在同一结构中的另一个容器中引用(当主all_ops容器被清除时,used_ops访问将如预期的那样变得非法(

当然,可以使用Rc,但它会导致性能问题。

你有正确的想法吗?(即一种在不久的将来不会成为硬错误的方式(。

trait Op {
fn f(&self);
}
struct OpA;

impl Op for OpA {
fn f(&self) {
println!("OpA");
}
}
struct OpB;
impl Op for OpB {
fn f(&self) {
println!("OpB");
}
}
struct Container<'a> {
all_ops: Vec<Box<dyn Op>>,
used_ops: Vec<&'a Box<dyn Op>>, // data pointing to data in all_ops field
}
fn main() {
let v: Vec<Box<dyn Op>> = vec![Box::new(OpA), Box::new(OpB)];
let mut c = Container { all_ops: v, used_ops: Vec::new() };
c.used_ops.push(&c.all_ops.get(0).unwrap());
c.used_ops.push(&c.all_ops.get(1).unwrap());
c.used_ops.push(&c.all_ops.get(0).unwrap());
for op in c.used_ops {
op.f();
}
c.all_ops.clear();
// c.used.first().unwrap().f(); // cannot borrow `c.all` as mutable because it is also borrowed as immutable
}

锈蚀操场

如果我替换used_ops: Vec<&'a Box<dyn Op>>通过used_ops: Vec<&'a dyn Op>,似乎足以修复警告。

不幸的是,即使used_ops中的所有引用都在堆中分配的对象上,Container也是不可移动的(我理解为什么,因为有对对象(内部(的引用(。

trait Op {
fn f(&self);
}
struct OpA;

impl Op for OpA {
fn f(&self) {
println!("OpA");
}
}
struct OpB;
impl Op for OpB {
fn f(&self) {
println!("OpB");
}
}
struct Container<'a> {
all_ops: Vec<Box<dyn Op>>,
used_ops: Vec<&'a dyn Op>, // data pointing to data in all_ops field
}
fn main() {
let v: Vec<Box<dyn Op>> = vec![Box::new(OpA), Box::new(OpB)];
let mut c = Container { all_ops: v, used_ops: Vec::new() };
c.used_ops.push(c.all_ops.get(0).unwrap().as_ref());
c.used_ops.push(c.all_ops.get(1).unwrap().as_ref());
c.used_ops.push(c.all_ops.get(0).unwrap().as_ref());
for op in c.used_ops.iter() {
op.f();
}
// let c2 = c; // cannot move out of `c` because it is borrowed
}

游乐场

最新更新