【发布时间】:2019-03-18 16:54:23
【问题描述】:
我有下面的代码来计算忽略标点符号的字数。
use std::collections::HashMap;
fn word_count(words: &str) -> HashMap<String, u32> {
let mut hm: HashMap<String, u32> = HashMap::new();
words
.split_whitespace()
.map(|word| word.trim_end_matches(char::is_ascii_punctuation))
.map(|word| {
hm.entry(word.to_string())
.and_modify(|val| *val += 1)
.or_insert(0)
});
hm
}
但是编译器抱怨
error[E0631]: type mismatch in function arguments
--> src/lib.rs:7:26
|
7 | .map(|word| word.trim_end_matches(char::is_ascii_punctuation))
| ^^^^^^^^^^^^^^^^
| |
| expected signature of `fn(char) -> _`
| found signature of `for<'r> fn(&'r char) -> _`
|
= note: required because of the requirements on the impl of `std::str::pattern::Pattern<'_>` for `for<'r> fn(&'r char) -> bool {std::char::methods::<impl char>::is_ascii_punctuation}`
我无法弄清楚该错误的真正含义或我的用法与trim_end_matches 文档中的用法有何不同:assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
【问题讨论】:
-
除了我的回答之外,我建议将最终的
map更改为for循环。将副作用放在map函数中并不是很好的风格,并且会导致借用问题,这在此处是不必要的。这是我将如何解决它:play.rust-lang.org/… -
@PeterHall 谢谢你的建议。在阅读下面的答案后,我只是在尝试这种方法。再次感谢。