なぜこれが生涯のエラーはありません。不変参照の代わりに構造体に可変参照を使用すると、生涯エラーが発生するのはなぜですか?
fn main() {
struct f<'a> {
x: &'a i32,
}
impl<'a, 'b> f<'a> {
fn get(&'b self) -> &'a i32 {
self.x
}
}
let x = 3;
let y = f { x: &x };
let z = f::get(&y);
}
をしかし、この
fn main() {
struct f<'a> {
x: &'a mut i32,
}
impl<'a, 'b> f<'a> {
fn get(&'b self) -> &'a i32 {
self.x
}
}
let mut x = 3;
let y = f { x: &mut x };
let z = f::get(&y);
}
は、このエラーが発生しました:
error[E0312]: lifetime of reference outlives lifetime of borrowed content...
--> src/main.rs:7:13
|
7 | self.x
| ^^^^^^
|
note: ...the reference is valid for the lifetime 'a as defined on the block at 6:36...
--> src/main.rs:6:37
|
6 | fn get(&'b self) -> &'a i32 {
| ^
note: ...but the borrowed content is only valid for the lifetime 'b as defined on the block at 6:36
--> src/main.rs:6:37
|
6 | fn get(&'b self) -> &'a i32 {
| ^
help: consider using an explicit lifetime parameter as shown: fn get(&'a self) -> &'a i32
--> src/main.rs:6:9
|
6 | fn get(&'b self) -> &'a i32 {
| ^
私は正確には分かりませんが、fのxをもう変更できないので、2番目の例が失敗することが重要であると思います。 – torkleyy
注: 'f'は' F'でなければならず、 'y.get()'を直接呼び出すことができます。この質問は本当に好きです! –
うわー、私はしばらく時間を取ったが、私は最終的にここで何が起こっていたのか理解していると思うし、このウサギの穴を下って行くのは本当にクールだった。もう一度質問してくれてありがとう! –