下面的代码编译并运行,但会发出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
}发布于 2022-01-25 10:56:24
如果我用used_ops: Vec<&'a Box<dyn Op>>替换used_ops: Vec<&'a dyn Op>,那么修复这个警告就足够了。
不幸的是,即使Container中的所有引用都是在堆中分配的对象上(而且我理解为什么会引用对象的内部部分),used_ops也是不可移动的。
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
}https://stackoverflow.com/questions/70799257
复制相似问题