Open
Description
struct Data{
s:& 'static str
}
fn main(){
let mut d = Data{s:"abc"};
{
let s = String::from("efg");
d.s = s.as_str(); // error, lifetime mismatched
}
}
As a contrast
struct Data2<'a>{
v:& 'a i32
}
fn main(){
let i = 1;
let mut d = Data2{v:&i}; // #1 the lifetime parameter is the same as `i`
{
let ii = 0;
d.v = ⅈ //#2 it's ok, without the above error says that mismatched lifetime
println!("{}",*d.v); // ok print 0
d.v = &i; //#3 try to switch the reference
}
v.d; //#4 this sentence reports an error
}
It is obscure here. Such two examples have inconsistent behaviors. For the second case, they are two issues
- The lifetime parameter seems not to be a constant value after the initialization at
#1
(i.e. it didn't keep the value of lifetime inferred at that point). It seems that the value can be changed at#2
and turned into a shorter lifetime, which results in#4
is an error. Unlike the first case, the lifetime of the field keeps not change once we specify the lifetime parameter.
- From observing
#3
and#4
, the value of the lifetime will be narrowed when we assign the reference with a shorter lifetime, and subsequently, the value cannot turn to longer even though we instead assign the reference with a longer lifetime value.
These are two obscure points. It should make sense that the access to v.d
at #4
is valid since we have changed the reference value at #3
to make it refers to i
that is valid at #4
.