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

被刻印的时光 ゝ 提交于 2019-11-26 23:12:13

问题


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<'a, T> {
    x: &'a T,
}
error[E0309]: the parameter type `T` may not live long enough
 --> src/main.rs:2:5
  |
2 |     x: &'a T,
  |     ^^^^^^^^
  |
  = help: consider adding an explicit lifetime bound `T: 'a`...
note: ...so that the reference type `&'a T` does not outlive the data it points at
 --> src/main.rs:2:5
  |
2 |     x: &'a T,
  |     ^^^^^^^^

I can fix it by changing to

pub struct NewType<'a, T>
where
    T: 'a,
{
    x: &'a T,
}

I don't understand why it is necessary to add the T: 'a part to the structure definition. I cannot think of a way that the data contained in T could outlive the reference to T. The referent of x needs to outlive the NewType struct and if T is another structure then it would need to meet the same criteria for any references it contains as well.

Is there a specific example where this type of annotation would be necessary or is the Rust compiler just being pedantic?


回答1:


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.



来源:https://stackoverflow.com/questions/38626644/why-does-the-rust-compiler-request-i-constrain-a-generic-type-parameters-lifeti

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!