在哈希映射中存储对向量项的引用时,绑定的寿命不够长

Binding does not live long enough when storing a reference to a vector item in a hash map

我是 Rust 的新手,仍在与借用检查器和正确的生命周期作斗争。

这是我开始构建的一个简单结构 - 它存储命令行参数的集合,例如东西(可以用 --string-c 或两者表示):

struct OptionMap<'a, T: 'a> {
    name: HashMap<String, &'a T>,
    short_name: HashMap<char, &'a T>,
    options: Vec<T>
}

impl<'a, T: 'a> OptionMap<'a, T> {
    pub fn new() -> OptionMap<'a, T> {
        OptionMap {
            name: HashMap::new(),
            short_name: HashMap::new(),
            options: Vec::new()
        }
    }

    pub fn register(&mut self, name: &OptionName, option: T) {        
        if name.name.is_some() {
            self.name.insert(name.name.unwrap().to_owned(), &option);
        }

        if name.short_name.is_some() {
            self.short_name.insert(name.short_name.unwrap(), &option);
        }

        self.options.push(option);
    }
}

我遇到了两个这样的错误(一个错误对应我写的 &option 个参数):

   Compiling glam v0.1.0 (file:///Users/carson/Projects/glam)
src/options.rs:57:66: 57:72 error: `option` does not live long enough
src/options.rs:57                 self.name.insert(name.name.unwrap().to_owned(), &option);
                                                                                   ^~~~~~
src/options.rs:54:62: 66:6 note: reference must be valid for the lifetime 'a as defined on the block at 54:61...
src/options.rs:54     pub fn register(&mut self, name: &OptionName, option: T) {
src/options.rs:55         {
src/options.rs:56             if name.name.is_some() {
src/options.rs:57                 self.name.insert(name.name.unwrap().to_owned(), &option);
src/options.rs:58             }
src/options.rs:59         }
                  ...
src/options.rs:54:62: 66:6 note: ...but borrowed value is only valid for the scope of parameters for function at 54:61
src/options.rs:54     pub fn register(&mut self, name: &OptionName, option: T) {
src/options.rs:55         {
src/options.rs:56             if name.name.is_some() {
src/options.rs:57                 self.name.insert(name.name.unwrap().to_owned(), &option);
src/options.rs:58             }
src/options.rs:59         }
                  ...

我传递了对每个哈希映射的引用(因此他们借用了它),然后将选项直接传递给向量以将其移动到那里,这样选项就不会超出范围。

似乎 'a 的范围和 option 的范围对我来说应该是一样的——因为 OptionMap 是在生命周期 'a 中创建的,并且 T 也受该生命周期的约束,并且 option 在函数末尾移入 options 。我错过了什么?我觉得我一直在与 Rust 的生命周期作斗争,就像我还没有点击的东西一样。

I pass a reference to each of the hash maps (so they borrow it) and then pass the option straight to the vector to move it there, so that the option doesn't go out of scope.

东西一旦借出,就不能再移到别处

如果将元素放入向量中并从那里借用它,则在借用结束之前不能改变向量。

换句话说,你目前的做法是行不通的。

最简单的解决方案可能是将索引存储到哈希映射中的向量中。

或者,可以设计一个可以与短名称和长名称进行比较的奇特键,然后您可以将选项直接存储在单个哈希映射中。我说 "might" 是因为我不确定目前是否可行。