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() {}
( Playground )
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。我知道 getter 在 Rust 中不能很好地工作,并且正确封装的集合不应该有一个可变的 get
,但这是我从不同语言移植的一些代码,所以我没有执行任何目前正在重构(只是移植和覆盖测试)。那里的生命周期问题是什么?
最佳答案
与
pub fn broken(&mut self) -> &mut Data {
&mut self.foos.first_mut().unwrap().data_mut()
}
核心问题是 data_mut()
的返回类型已经是一个 &mut Data
值,所以你实际上是在创建一个 &mut &mut Data
,尽管那会崩溃。在您的情况下,最简单的解决方法是完全删除 &mut
pub fn broken(&mut self) -> &mut Data {
self.foos.first_mut().unwrap().data_mut()
}
看起来,通过添加 &mut
,您会导致借用检查器创建一个临时位置,然后引用该位置。
关于rust - setter/getter 中的可变借用时间不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51502717/