-3

Consider the following:

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;
}

I get the error:

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

I understand the meaning of this error, but not I'm sure how to implement the fix. Do I need to make adventure_list mutable?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
SeekingTruth
  • 1,044
  • 2
  • 15
  • 23
  • 3
    The quick solution is to remove the `&` from `&i32`, you almost certainly want a 32 bit integer as your key, not a reference to a 32 bit integer. – 8176135 Jul 15 '20 at 06:20
  • Consider re-reading the relevant section of the book: [Chapter 4, What is Ownership?](https://doc.rust-lang.org/stable/book/ch04-01-what-is-ownership.html) – E_net4 Jul 15 '20 at 08:03
  • Does this answer your question? [How do I fix a missing lifetime specifier?](https://stackoverflow.com/questions/43330616/how-do-i-fix-a-missing-lifetime-specifier) – E_net4 Jul 15 '20 at 08:07

1 Answers1

2

I guess you want to map numbers to callbacks. But what you wrote is mapping references to numbers to callbacks.

Now, references have a lifetime. In your case, you start out with count - which lives only inside your function. Thus, even if you wanted to refer (i.e. have a reference) to it in your result, this would go wrong, as count goes out of scope at the end of the function.

What you almost certainly want, is your result type to be HashMap<i32, SimpleCallback>.

Remark: Since references have lifetimes, Rust suggests to add a static lifetime, meaning that you have references to numbers that are available for the whole run of the program (as opposed to only within your function). But, as said, you almost certainly do not want references to numbers, but simply numbers.

phimuemue
  • 34,669
  • 9
  • 84
  • 115