Eli Sadoff
Eli Sadoff

Reputation: 7308

How can I specify the type of the Some parameter in Rust?

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.

Upvotes: 1

Views: 119

Answers (1)

mcarton
mcarton

Reputation: 30001

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

Upvotes: 3

Related Questions