1

I am working on a program in Rust and I am getting stuck on match. I currently have

extern crate regex; use std::collections::HashMap; fn main() { let s = ""; let re = regex::Regex::new(r"[^A-Za-z0-9\w'").unwrap(); let s = re.split(s).collect::<Vec<&str>>(); let mut h: HashMap<String, u32> = HashMap::new(); for x in s { match h.get(x) { Some(i) => h.entry(x.to_string()).or_insert_with(i + 1), None => h.entry(x.to_string()).or_insert_with(1), } } } 

but when I run this I get a whole litany of errors, including

error: the trait bound `u32: std::ops::FnOnce<()>` is not satisfied [E0277] Some(i) => h.entry(x.to_string()).or_insert_with(i + 1), ^~~~~~~~~~~~~~ 

and I'm not exactly sure where to go with this.

1

1 Answer 1

3

The or_with family of functions expect a function that returns the values as a parameter. You want .or_insert, which directly expects the value:

let re = regex::Regex::new(r"[^A-Za-z0-9\w'").unwrap(); let s = re.split(s).collect::<Vec<&str>>(); let mut h: HashMap<String, u32> = HashMap::new(); for x in s { match h.get(x) { Some(i) => h.entry(x.to_string()).or_insert(i + 1), None => h.entry(x.to_string()).or_insert(1), } } 

Anyway, you are missing the point of the Entry API:

let re = regex::Regex::new(r"[^A-Za-z0-9\w'").unwrap(); let s = re.split(s).collect::<Vec<&str>>(); let mut h: HashMap<String, u32> = HashMap::new(); for x in s { match h.entry(x.to_string()) { Entry::Vacant(v) => { v.insert(1); }, Entry::Occupied(o) => { *o.into_mut() += 1; }, } } 
Sign up to request clarification or add additional context in comments.

5 Comments

When I use or_insert I get mismatched types: expected `()` found `&mut u32`
That's because or_insert returns &mut _ but the loop body must have a unit type. I've edited my answer anyway.
Thank you! The Entry API is fantastic.
I think you really want *h.entry(x.to_string()).or_insert(0) += 1;
@EliSadoff: I was blown away when Gankro unveiled it :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.