rust - 为什么这个结构成员需要两个生命周期?

标签 rust lifetime

我有以下 struct :

struct PeekableRead<'a, R: Read> {
    reader: &'a mut R,
    peeked_octet: Option<u8>,
}

哪个rustc不喜欢:

…:27:1: 30:2 error: the parameter type `R` may not live long enough [E0309]
…:27 struct PeekableRead<'a, R: Read> {
…:28    reader: &'a mut R,
…:29    peeked_octet: Option<u8>,
…:30 }
…:27:1: 30:2 help: run `rustc --explain E0309` to see a detailed explanation
…:27:1: 30:2 help: consider adding an explicit lifetime bound `R: 'a`...
…:27:1: 30:2 note: ...so that the reference type `&'a mut R` does not outlive the data it points at
…:27 struct PeekableRead<'a, R: Read> {
…:28    reader: &'a mut R,
…:29    peeked_octet: Option<u8>,
…:30 }

如果我将生命周期添加到 R ,如 R: Read + 'a , 有用。但是为什么'a 不是吗?在引用上指定生命周期?绝不能reader: &'a mut R , 在 struct PeekableRead<'a>与结构本身一样长,因此“足够长”?

奇怪的是,我似乎两者都需要;如果我添加 'aR并将其从引用中删除,我仍然得到 error: missing lifetime specifier .我获得成功编译的唯一方法是同时使用两者,但对我来说,它们似乎冗余地指定了同一件事。

(另外,为什么 rustc 在输出中输出了两次 struct?第二个看起来像是建议做什么,但似乎与我所拥有的完全一样……)

最佳答案

Doesn't the 'a on the reference specify the lifetime?

它指定引用 的生命周期,但不是指向的值的生命周期。这解释了您的观察结果

if I add 'a to R and remove it from the reference, I still get error: missing lifetime specifier.

为了使结构有效,我们需要两者:指向的值必须仍然存在,引用也必须如此。 (虽然从逻辑上讲,第一个条件隐含在第二个条件中,因为引用永远不会超过它指向的值。)

关于rust - 为什么这个结构成员需要两个生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36511601/

相关文章:

rust - futures-rs 在 `BoxStream` 上使用 Stream 组合器

rust - 从Iterator返回的对象中的可变引用

reference - 如何制作引用文献的副本? (生活问题)

rust - 如何将特质对象的Vec变成树形结构?

generics - 当泛型类型受到泛型生存期的限制时,这意味着什么?

rust - 延长变量的生命周期

rust - 是否可以创建 RefCell<Any>?

rust - Rust 的 where 子句中的特征可能有哪些运算符?

rust - 将字符串写入文件

rust - 创建一个迭代器并将其放入一个新的结构中而不打扰借用检查器