如何确保自身在不借入的情况下超过返回值

问题描述 投票:1回答:1

假设有这样的事情:

trait B {}
struct BB {}
impl B for BB {}

struct A {}
impl A {
    // With this, A can be dropped before B
    // fn get_b(&mut self) -> Box<dyn B> {...}

    fn get_b<'a>(&'a mut self) -> Box<dyn B + 'a> {...}
    fn mut_a(&mut self) {}
}

fn main() {
    let mut a = A {};
    let b = a.get_b();

    // These lines don't compile
    a.mut_a(); // A is borrowed. Is there any way to make this compile?

    // Does not compile and should not. b must be dropped before a
    drop(a);
    drop(b);
}

是否有任何方法可以确保a的寿命超过b(出于unsafe代码的原因)而没有借用a

编辑:ab都必须是可变的(如果声明为mut)并且应保持可移动状态。它唯一需要确保的是B在A之前被丢弃。

rust borrow-checker
1个回答
0
投票

如果给A两个字段,例如lifetimedata,则可以使get_b共享对lifetime的引用,并使mut_a可变地引用data

© www.soinside.com 2019 - 2024. All rights reserved.