对为何借来的价值不能长期使用存有误解

时间:2018-07-12 09:16:18

标签: rust borrow-checker

我在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

0 个答案:

没有答案