Skip to content

The inconsistent meaning of lifetime parameter in struct #99896

Open
@xmh0511

Description

@xmh0511
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 = &ii; //#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

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lifetimesArea: Lifetimes / regionsC-discussionCategory: Discussion or questions that doesn't represent real issues.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions