pub type Data = i32;
pub struct Foo {
data: Data,
}
impl Foo {
pub fn data_mut(&mut self) -> &mut Data {
&mut self.data
}
}
pub struct Context {
data: Data,
foos: Vec<Foo>,
}
impl Context {
pub fn broken(&mut self) -> &mut Data {
// What are the lifetimes here that make this version not work?
&mut self.foos.first_mut().unwrap().data_mut()
}
pub fn working(&mut self) -> &mut Data {
&mut self.foos.first_mut().unwrap().data
}
}
fn main() {}
error[E0597]: borrowed value does not live long enough
--> src/main.rs:21:14
|
21 | &mut self.foos.first_mut().unwrap().data_mut()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ temporary value does not live long enough
22 | }
| - temporary value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 19:5...
--> src/main.rs:19:5
|
19 | / pub fn broken(&mut self) -> &mut Data {
20 | | // What are the lifetimes here that make this version not work?
21 | | &mut self.foos.first_mut().unwrap().data_mut()
22 | | }
| |_____^
我不想将 data
字段设为公共的,所以我尝试使用一个 getter。我知道在 Rust 中 getter 的效果不佳,并且适当封装的集合不应该有可变的 get
方法,但这是我从另一种语言移植过来的代码,所以目前我没有进行任何重构(只是移植并覆盖测试)。那么其中的生命周期问题是什么?
&mut
,因为data_mut
已经返回了一个&mut Data
。https://play.rust-lang.org/?gist=b885337f7afd99e59ecb1bf62aaf2b3c&version=nightly&mode=debug&edition=2018 - loganfsmyth&mut
,甚至也给getter返回值加上了前缀。等待将您的答案标记为最佳答案。 - iwat0qs&mut
导致该结果变成了一个临时变量,代码试图返回对这个临时变量的引用,这在技术上是正确的,因为存在强制转换。 - iwat0qs