我有以下struct
:爲什麼這個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
兩次輸出?第二個看起來像什麼就做一個建議,但似乎是完全一樣的我有什麼...)
您可以考慮struct PeekableRead 「結構的外部可見API,而這些字段是實現細節。然而,這種動機不是一個通用規則,因爲我們可以考慮結構的某些屬性,這些屬性沒有像這樣明確拼寫出來(每個泛型參數和自動特徵的方差)。 – bluss