Rust 的生命周期再次让我感到困惑。我正在尝试返回对我拥有的盒装对象的可变引用。这是我的问题简化:
pub trait Foo {
fn foo(&self);
}
pub struct Bar {
foo: Option<Box<Foo>>,
}
impl Bar {
pub fn foo(&mut self) -> &mut Box<Foo> {
let foo_ref = self.foo.as_mut();
foo_ref.unwrap()
}
pub fn set_foo(&mut self, value: Box<Foo>) {
self.foo = Some(value);
}
}
我收到这些错误,我不太明白:
Compiling testproject v0.0.1 (file:///home/virtlink/projects/orion/testproject)
src/lib.rs:15:17: 15:25 error: cannot infer an appropriate lifetime due to conflicting requirements
src/lib.rs:15 foo_ref.unwrap()
^~~~~~~~
src/lib.rs:15:9: 15:25 note: first, the lifetime cannot outlive the method call at 15:8...
src/lib.rs:15 foo_ref.unwrap()
^~~~~~~~~~~~~~~~
src/lib.rs:15:9: 15:16 note: ...so that method receiver is valid for the method call
src/lib.rs:15 foo_ref.unwrap()
^~~~~~~
src/lib.rs:13:44: 16:6 note: but, the lifetime must be valid for the anonymous lifetime #1 defined on the block at 13:43...
src/lib.rs:13 pub fn foo(&mut self) -> &mut Box<Foo> {
src/lib.rs:14 let foo_ref = self.foo.as_mut();
src/lib.rs:15 foo_ref.unwrap()
src/lib.rs:16 }
src/lib.rs:15:9: 15:25 note: ...so that expression is assignable (expected `&mut Box<Foo>`, found `&mut Box<Foo>`)
src/lib.rs:15 foo_ref.unwrap()
^~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `testproject`.
我不知道如何解决这个问题。