我在Rust中遇到一个错误,我不明白为什么要面对它。
我有一个自定义Reader
对象,该对象拥有一个Vec
对象中的IFD
和一个HashMap
,其对象引用了所拥有的某些IFDEntry
元素第一个向量内的IFD
元素:
// `IFD` owns some `IFDEntry`
pub struct IFD {
pub entries: Vec<IFDEntry>,
pub next: usize,
}
pub struct Reader<'a, R> {
inner: R,
order: Endian,
ifds: Vec<IFD>, // Reader owns the list of `IFD` here
entries_map: HashMap<Tag, &'a IFDEntry>,
}
此对象定义了new
函数充电,用于填充与某些std::io::BufRead
元素一致的那些元素。在此功能结束时:
let mut map = HashMap::<Tag, &IFDEntry>::new();
// ifds owns the differents values here
let ifds: Vec<IFD> = IFDIterator::new(&mut reader, order, offset as usize).collect();
// We fill the map with references
for ifd in &ifds {
for entry in &ifd.entries {
map.insert(entry.tag, entry);
}
}
// Move from both `map` and `ifds` inside the `Reader`
Ok(Reader {
inner: reader,
order: order,
ifds: ifds,
entries_map: map,
})
编译器抱怨ifds
的生存时间不够长(第68行对应于Ok(Reader)
的返回):
error[E0597]: `ifds` does not live long enough
--> src/reader.rs:56:21
|
56 | for ifd in &ifds {
| ^^^^ borrowed value does not live long enough
...
68 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 16:6...
据我了解,ifds
在函数结尾处移至Reader
内。那么为什么它寿命不长?
整个文件可以在这里找到:https://github.com/yageek/tiff/blob/develop/src/reader.rs