Confused about lifetimes

I'm new to Rust and trying to wrap my head around lifetimes.
Here's a little example I would like to have explained:

struct Test { x: i32 };
let a;
{
    let b = &Test{ x: 42 }; // Temporary struct Test put on the stack
    a = b;
} // Temporary Test dropped here?
    
println!("{}", a.x); // Temporary Test used here?

I don't understand why this code is OK. It seems weird to be allowed to reference something I don't have an explicit ownership of, if that makes sense.
When is the temporary Test struct dropped? Never?

The compiler allows you to declare a variable without it being initialized as long as it can prove it will be initialized before use.

let a; // declare uninitialized value

{
    a = b; // the compiler knows this will always run before
}
println!("{}", a.x) // the only use is after the `a` is initialized

try this

1 Like

What happened here is the same that happens to a literal string. The constant is hard coded somewhere in the binary and the reference is a 'static reference that points into the executable.

1 Like

Is the reference made 'static by the compiler when resolving types, as that is the only possible type to satisfy a outliving the closure?

Yes. The details are in RFC 1414.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.