Why does the Rust compiler request I constrain a generic type parameter's lifetime (error E0309)?

前端 未结 1 1137
长情又很酷
长情又很酷 2020-12-03 12:51

Why does the Rust compiler emit an error requesting me to constrain the lifetime of the generic parameter in the following structure?

pub struct NewType<\         


        
相关标签:
1条回答
  • 2020-12-03 13:41

    What T: 'a is saying is that any references in T must outlive 'a.

    What this means is that you can't do something like:

    let mut o: Option<&str> = Some("foo");
    let mut nt = NewType { x: &o };  // o has a reference to &'static str, ok.
    
    {
        let s = "bar".to_string();
        let o2: Option<&str> = Some(&s);
        nt.x = &o2;
    }
    

    This would be dangerous because nt would have a dangling reference to s after the block. In this case it would also complain that o2 didn't live long enough either.

    I can't think of a way you can have a &'a reference to something which contains shorter-lifetime references, and clearly the compiler knows this in some way (because it's telling you to add the constraint). However I think it's helpful in some ways to spell out the restriction, since it makes the borrow checker less magic: you can reason about it just from just type declarations and function signatures, without having to look at how the fields are defined (often implementation details which aren't in documentation) or how the implementation of a function.

    0 讨论(0)
提交回复
热议问题