Hi-Angel
Hi-Angel

Reputation: 5659

How do I create a Vec of Entries from a HashMap?

Given a HashMap<Token, Frequency>, I want a Vec of references to these pairs. I found that the pairs are of type Entry, so it would look something like:

use std::collections::HashMap;

type Freq = u32;
type Token = String;

struct TokenizeState {
    tokens: HashMap<Token, Freq>,
    text: Vec<std::collections::hash_map::Entry<Token, Freq>>,
}

fn main() {}

This code has an error:

error[E0106]: missing lifetime specifier
 --> src/main.rs:8:15
  |
8 |     text: Vec<std::collections::hash_map::Entry<Token, Freq>>,
  |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected lifetime parameter

Adding a lifetime specifier to the struct leads to the same error:

struct TokenizeState<'a> {
    tokens: HashMap<Token, Freq>,
    text: Vec<&'a std::collections::hash_map::Entry<Token, Freq>>,
}

My main problem is that I don't know if std::collections::hash_map::Entry<Token, Freq> is the correct type. I have experimented with a lot things, like the more obvious HashMap<Token, Freq>::Entry, and couldn't get it work.

Upvotes: 0

Views: 118

Answers (1)

starblue
starblue

Reputation: 56822

The lifetime is needed on Entry, as you can see in the documentation. Like this:

struct TokenizeState<'a> {
    tokens: HashMap<Token, Freq>,
    text: Vec<std::collections::hash_map::Entry<'a, Token, Freq>>,
}

Upvotes: 1

Related Questions