代码如下:
#[derive(Debug)]
struct Point<'x, 'y> {
x: &'x i32,
y: &'y i32,
}
fn main() {
let x = 1;
let point: Point;
{
let y = 2;
point = Point { x: &x, y: &y };
}
print!("{:?}", point);
}
errror message 如下:
error[E0597]: `y` does not live long enough
--> src/main.rs:224:35
|
224 | point = Point { x: &x, y: &y };
| ^^ borrowed value does not live long enough
225 | }
| - `y` dropped here while still borrowed
226 | print!("{:?}", point);
| ----- borrow later used here
我对 Point 这个 struct 已经声明了它的两个参数需要使用不同的生命周期,并且我的 main 函数中也模拟了不同的生命周期,编译器提示我无法通过,但是这个错误信息我也看的懂,就是 y 变量的生命周期不够长,但是我还是很好奇我明明声明的字段就是不同的生命周期啊?如果坚持使用引用的话,如何修改可以让代码编译通过?感谢🙏