我不明白 Rust 中的这个错误是什么意思:
error: lifetime of non-lvalue is too short to guarantee its contents can be safely reborrowed
什么是非左值? (我怀疑这不是正确的值)。
我想了解错误的含义,并能够从可变引用向量中修改“对象”。
这是产生错误的最小测试用例。我在一个向量中插入一个对结构的可变引用,然后尝试修改指向的结构。
struct Point {
x: uint,
y: uint
}
fn main() {
let mut p = Point { x: 0, y: 0};
p.x += 1; // OK, p owns the point
let mut v: Vec<&mut Point> = Vec::new();
v.push(&mut p);
// p.x += 1 // FAIL (expected), v has borrowed the point
let p1:&mut Point = *v.get_mut(0); // ERROR, lifetime of non-lvalue...
// never reached this line
// p1.x += 1;
}
最佳答案
让我们回顾一下您在这里要做什么:
let p1:&mut Point = *v.get_mut(0);
*v.get_mut(0)
首先返回对向量中可变引用的可变引用,然后取消引用它。如果这样编译,您最终会得到对同一对象的两个可变引用:一个在 vector 中,另一个在 p1 变量中。 Rust 拒绝这样做,因为它不安全。
到目前为止,最好的解决方案是让向量成为您的 Point
的所有者。对象。 IE。使用Vec<Point>
而不是 Vec<&mut Point
.
如果您需要更复杂的东西,您可以使用 RefCell 来动态检查借用:
use std::cell::RefCell;
struct Point {
x: uint,
y: uint
}
fn main() {
let p = RefCell::new(Point { x: 0, y: 0});
p.borrow_mut().x += 1;
let mut v: Vec<&RefCell<Point>> = Vec::new();
v.push(&p);
let p1 = v.get(0);
p1.borrow_mut().x += 1;
p.borrow_mut().x += 1;
}
关于使用rust :错误:非左值的生命周期太短,无法保证其内容可以安全地重新借用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24841495/