I have the following code I am surprised works:
struct S<'a> {
value: &'a String,
}
fn foo(s: &S) {
println!("{}", s.value);
}
#[allow(dead_code)]
fn main() {
let s = S {
value: &String::from("ABC"),
};
foo(&s);
}
If I see a pair of curly braces, I imagine them as a scope. So for me, the line S { value: &String::from("ABC") };
and, more importantly, the part between the curly braces represents a scope. Inside this scope, an anonymous string is created and a reference to it is taken. After the brace is closed, the string should be destroyed and the next line foo(&s)
should tell me something about lifetimes, but this is not the case! Why?