[英]Need help on lifetime issue
pub struct Decoder<'a> {
reader: &'a mut io::Reader+'a,
}
impl<'a> Decoder<'a> {
pub fn from_reader(r: &'a mut io::Reader) -> Decoder<'a> {
Decoder {
reader: r,
}
}
}
// shortcut method to accept bytes to decode
pub fn decode<'a, T: Decodable<Decoder<'a>, IoError>>(data: Vec<u8>) -> DecodeResult<T> {
let mut r = MemReader::new(data);
let mut decoder = Decoder::from_reader(&mut r); // error: `r` does not live long enough
Decodable::decode(&mut decoder)
}
我在這里有兩個問題。
reader: &'a mut io::Reader+'a
。 我正在引用來自std json編碼器的代碼。 Vec<u8>
,這樣我就可以與io :: Reader接口。 但是編譯器抱怨error:
r does not live long
。 如何使其正確。 更新:我將代碼上傳到github 。
第一個'a
表示Reader
對象本身具有壽命'a
。 第二個'a
表示Reader
對象不包含壽命超過'a
引用。 由於Reader
是一個特征,因此可以通過具有生命周期參數的結構來實現。 此限制適用於那些潛在的壽命參數。
問題在於T
上的界限: Decodable<Decoder<'a>, IoError>
引用生存期參數'a
。 但是,您正在創建的Decoder
引用一個局部變量,而'a
表示生命周期長於函數調用(因為它是在調用站點隱式指定的輸入參數)。
我認為目前沒有不安全的代碼無法使該函數成功編譯。 實際上, Encoder::buffer_encode
似乎有相同的問題( #14302 ),並使用類似的解決方法。 transmute
允許我們將本地生命周期強制為'a
。
pub fn decode<'a, T: Decodable<Decoder<'a>, IoError>>(data: Vec<u8>) -> DecodeResult<T> { let mut r = MemReader::new(data); let mut decoder = unsafe { mem::transmute(Decoder::from_reader(&mut r)) }; Decodable::decode(&mut decoder) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.