首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >结构内部的共享所有权(mutable_borrow_reservation_conflict警告)

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

Stack Overflow用户
提问于 2022-01-21 09:44:31
回答 1查看 114关注 0票数 3

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

我的目标是让字段all_ops拥有一组op的实现(只读),其中每个op可以在同一个结构中的另一个容器中引用(当主all_ops容器被清除时,used_ops访问就像预期的那样成为非法的)。

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

你有办法做好吗?(也就是说,一种不会成为(接近?)的严重错误的方式。未来)。

代码语言:javascript
复制
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
}

生锈操场

EN

回答 1

Stack Overflow用户

发布于 2022-01-25 10:56:24

如果我用used_ops: Vec<&'a Box<dyn Op>>替换used_ops: Vec<&'a dyn Op>,那么修复这个警告就足够了。

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

代码语言:javascript
复制
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
}

游乐场

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70799257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档