我有一些包含一些数据的 struct ,看起来像这样:
struct A {
// Some data
}
struct B<'s> {
a: &'s mut A
c: C<'s>
}
impl<'s> B<'s> {
fn new(a: &'s mut A, d: &'s D) -> B<'s> {
let c = C::new(d);
B { a, c }
}
fn extract_c(self) -> C<'s> {
self.c
}
}
// A smart pointer provided by a library
struct C<'s> {
d: &'s D,
// Other fields holding some data, not referencing A
}
struct D {
// Some other data not referencing A in any way (provided by a library)
}
我也有创建和修改所述 struct 的函数,如下所示:
fn modify(b: &mut B) {
// Modifies b.a and b.c
}
fn construct_c<'s>(a: &'s mut A, d: &'s D) -> C<'s> {
let mut b = B::new(a, d); // C is created in B::new
modify(&mut b);
b.extract_c()
}
我想在其他地方使用construct_c
,以便在从调用中获得结果后可以再次引用A,如下所示:
fn main() {
let mut a = A::new();
let d = D::new();
let c = construct_c(&mut a, &d); // First mutable borrow of `a`
println!("{a}"); // Second borrow of `a`
let result = do_sth_with_c(c); // Move of `c`
do_sth_with_a(a);
// Some other code...
}
然而,当我try 这样做时,编译器告诉我,当我调用do_sth_with_c
时,我使用的是a
的第一个可变借入,尽管c
没有保存提供给construct_c
的对a
的引用.
当我删除println!("{a}");
和do_sth_with_a
时,代码会编译,但我确实需要打印该信息,并在呼叫do_sth_with_c
之前打印出来.有没有办法告诉编译器C
对a
的引用一无所知,并且在调用construct_c
之后可以安全地进行新的引用?
EDIT 1:
当我将所有引用&mut A
替换为Rc<RefCell<A>>
时,代码编译.但是有没有其他不用Rc
和RefCell
的方法呢?
一百零二
在this answer岁之后,B
岁再活一年似乎就解决了这个问题.
How 100 changed:
struct B<'a, 's> {
a: &'a mut A,
c: C<'s>,
}
// All functions that use `B` need to be updated as well