繁体   English   中英

如何在Rust中指定Some参数的类型?

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

我正在研究Rust的一个程序,我在match陷入困境。 我现在有

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

但是当我运行这个时,我会得到一连串的错误,包括

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

而且我不确定该去哪里。

or_with系列函数需要一个将值作为参数返回的函数。 你想要.or_insert ,它直接期望值:

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

无论如何,你错过了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;
      },
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM