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()