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

。_饼干妹妹 提交于 2019-11-27 22:37:08

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.

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