This first Rust program won't compile because b
is dropped before its reference r
, which makes sense:
fn main() {
let a = "a";
let v;
{
let b = "b";
v = &b;
}
println!("{}", v);
}
In this second Rust program, a reference to b
is retrieved via a function, and all of the sudden there's no issue:
fn getRef(b: &str) -> &str {
b
}
fn main() {
let a = "a";
let v;
{
let b = "b";
v = getRef(&b);
}
println!("{}", v);
}
The thing is, v
is still a reference to b
, and b
is out of scope for the println!()
.
Why are these two different?