struct Parent<'a> {
inner: Option<&'a mut Object>
}
impl<'a> Parent<'a> {
fn new() -> Parent<'a> {
Parent {
inner: None,
}
}
fn bind(&mut self, obj: &'a mut Object) {
self.inner = Some(obj);
}
fn unbind(&mut self) {
self.inner = None;
}
}
struct Object {
inner: u32,
}
fn main() {
let mut obj = Object { inner: 0 };
let mut parent1 = Parent::new();
let mut parent2 = Parent::new();
parent1.bind(&mut obj);
parent1.unbind();
// parent2.bind(&mut obj);
// ^ error
}
结构Parent
字段必须存储Option
:
struct Parent {
inner: Option</* magic */>
}
有必要暂时阻止在 fn main()
中使用对象的可能性,直到调用 .unbind()
最佳答案
借用检查器不可能在编译时证明这是正确的。但是您可以使用 RefCell
来确保它在运行时正常工作,并且如果您做错了会出现 panic 。您可以存储一个允许修改对象的 RefMut
,而不是在 Parent 对象中存储对该对象的引用。 bind
函数获取对 RefCell
的引用,如果该对象已被借用,则会出现 panic。
use std::cell::*;
struct Parent<'a> {
inner: Option<RefMut<'a, Object>>,
}
impl<'a> Parent<'a> {
fn new() -> Parent<'a> {
Parent {
inner: None,
}
}
fn bind(&mut self, obj: &'a RefCell<Object>) {
self.inner = Some(obj.borrow_mut());
}
fn unbind(&mut self) {
self.inner = None;
}
}
struct Object {
inner: u32,
}
fn main() {
let obj = RefCell::new(Object { inner: 0 });
let mut parent1 = Parent::new();
parent1.bind(&obj);
parent1.unbind(); // comment this line out and you get a runtime panic
let mut parent2 = Parent::new();
parent2.bind(&obj);
}
关于rust - 暂时持有借来的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33562359/