我有以下 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>
与结构本身一样长,因此“足够长”?
奇怪的是,我似乎两者都需要;如果我添加 'a
至 R
并将其从引用中删除,我仍然得到 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/