假设有这样的事情:
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
?
编辑:a
和b
都必须是可变的(如果声明为mut
)并且应保持可移动状态。它唯一需要确保的是B在A之前被丢弃。
如果给A
两个字段,例如lifetime
和data
,则可以使get_b
共享对lifetime
的引用,并使mut_a
可变地引用data
: