【问题标题】:Missing lifetime specifier in returned HashMap<&i32, SimpleCallback>返回的 HashMap<&i32, SimpleCallback> 中缺少生命周期说明符
【发布时间】:2020-07-15 06:04:49
【问题描述】:

考虑以下几点:

use std::collections::HashMap;
use std::vec::Vec;
use crate::core::process_call_backs::SimpleCallback;

pub fn make_adventure_list(adventure_list: Vec<SimpleCallback>) -> HashMap<&i32, SimpleCallback> {
    let mut adventures = HashMap::new();

    let mut count = 1;

    for adventure in adventure_list {
        adventures.insert(count, adventure);

        count = count + 1;
    }

    adventures;
}

我得到错误:

error[E0106]: missing lifetime specifier
 --> core/src/core/create_adventures.rs:5:76
  |
5 | pub fn make_adventure_list(adventure_list: Vec<SimpleCallback>) -> HashMap<&i32, SimpleCallback> {
  |                                                                            ^ help: consider giving it an explicit bounded or 'static lifetime: `&'static`
  |
  = help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments

我了解此错误的含义,但不确定如何实施修复。我需要使adventure_list 可变吗?

【问题讨论】:

标签: rust


【解决方案1】:

我猜你想将数字映射到回调。但是你写的是将对数字的引用映射到回调。

现在,references 有了生命周期。在您的情况下,您从 count 开始 - 它仅存在于 您的函数中。因此,即使您想在结果中引用(即引用)它,这也会出错,因为 count 在函数末尾超出范围。

您几乎肯定想要的是结果类型为HashMap&lt;i32, SimpleCallback&gt;

备注: 由于引用有生命周期,Rust 建议添加 static 生命周期,这意味着您拥有对整个程序运行可用的数字的引用(而不是仅在你的功能)。但是,如前所述,您几乎可以肯定想要引用数字,而只是数字。

【讨论】:

    猜你喜欢
    • 2015-08-24
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 2014-12-29
    • 1970-01-01
    • 2016-02-18
    • 2011-07-29
    • 2023-03-24
    相关资源
    最近更新 更多