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
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.