gpt4 book ai didi

rust - 返回对链表元素的引用

转载 作者:行者123 更新时间:2023-11-29 08:05:12 25 4
gpt4 key购买 nike

我想实现一个实例化新元素的函数,将其添加到链表中,然后返回对它刚刚创建的元素的引用。这是我想出的:

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

我认为当我将返回的引用的生命周期绑定(bind)到 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

最佳答案

问题不在于Option 中的引用,而是Option 对象本身。按值而不是引用返回它。

impl Bar {
fn foo_alloc(&mut self) -> Option<&mut Foo> {
let foo = Foo{};
self.ll.push_back(foo);
self.ll.front_mut()
}
}

我还删除了生命周期注释,因为默认的生命周期扣除在这里做了正确的事情。

关于rust - 返回对链表元素的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42392250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com