tl;dr: [solved] it's the same as: [solved] Reference and Borrowing: Question about Life Time Good stuff!
Coming from: References and Borrowing (but without having read chapter 4 yet)
#[allow(unused_mut)]
#[allow(unused_variables)]
fn main() {
let mut y: &i32 = &1;
let z=6;
{
y = &z;
//let x=&z; //comment the above line and uncomment this one, for the next (working) test.
}
println!("{} {}", z, y);
}
<anon>:7:14: 7:15 error: `z` does not live long enough
<anon>:7 y = &z;
^
<anon>:4:26: 13:2 note: reference must be valid for the block suffix following statement 0 at 4:25...
<anon>:4 let mut y: &i32 = &1;
<anon>:5 let z=6;
<anon>:6 {
<anon>:7 y = &z;
<anon>:8 //let x=&z; //comment the above line and uncomment this one, for the next (working) test.
<anon>:9 }
...
<anon>:5:13: 13:2 note: ...but borrowed value is only valid for the block suffix following statement 1 at 5:12
<anon>: 5 let z=6;
<anon>: 6 {
<anon>: 7 y = &z;
<anon>: 8 //let x=&z; //comment the above line and uncomment this one, for the next (working) test.
<anon>: 9 }
<anon>:10
...
error: aborting due to previous error
playpen: application terminated with error code 101
,
error: `z` does not live long enough
Is it z
who does not live long enough or rather is it &z
(or y
) ?
Oh wait,
SOLVED: the following works, ergo my bad (it is z
which does not live long enough):
fn main() {
let z=6;
let y: &i32;
{
y = &z;
}
println!("{} {}", z, y);
}
I'll post this anyway, even though I've realized the error of my ways because I think it's interesting to see what I initially thought was going on and then realized the compiler was right all along. Hope it's okay with you. (added tl;dr so people don't waste time reading)