我想实现一个实例化一个新元素的函数,将它添加到一个链表然后返回它刚刚创建的元素的引用。这就是我想出的:
use std::collections::LinkedList;
struct Bar {
ll: LinkedList<Foo>
}
struct Foo {}
impl Bar {
fn foo_alloc<'a>(&'a mut self) -> &Option<&'a mut Foo> {
let foo = Foo{};
self.ll.push_back(foo);
&self.ll.front_mut()
}
}
我认为当我将返回的引用的生命周期绑定到Bar
实例(通过&'a mut self
)时,这应该足够了,但显然不是。
这是错误:
error: borrowed value does not live long enough
--> src/main.rs:14:10
|
14 | &self.ll.front_mut()
| ^^^^^^^^^^^^^^^^^^^ does not live long enough
15 | }
| - temporary value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the body at 11:59...
--> src/main.rs:11:60
|
11 | fn foo_alloc<'a>(&'a mut self) -> &Option<&'a mut Foo> {
| ____________________________________________________________^ starting here...
12 | | let foo = Foo{};
13 | | self.ll.push_back(foo);
14 | | &self.ll.front_mut()
15 | | }
| |_____^ ...ending here
答案 0 :(得分:4)
问题不是Option
内的引用,而是Option
对象本身。按值返回,而不是通过引用。
impl Bar {
fn foo_alloc(&mut self) -> Option<&mut Foo> {
let foo = Foo{};
self.ll.push_back(foo);
self.ll.front_mut()
}
}
我还删除了生命周期注释,因为默认的生命周期扣除在这里做了正确的事情。