This snippet doesn't compile because the struct A
instance outlives the reference s2
it holds in its field s
. No problem.
struct A<'a> {
s: &'a usize,
}
let s1 = 100;
let mut a = A { s: &s1 };
{
let s2 = 1000;
a.s = &s2;
}
In the same situation for string literals, it compiles. Why?
struct A<'a> {
s: &'a str,
}
let s1 = "abc";
let mut a = A { s: &s1 };
{
let s2 = "abcd";
a.s = &s2;
}