这个问题在这里已有答案:
use std::collections::HashSet;
fn character_count(needles: &HashSet<char>, needle_type: &str, input: &str) -> i32 {
for needle in needles {
let mut needle_custom;
if needle_type == "double" {
needle_custom = needle.to_string() + &needle.to_string();
} else {
needle_custom = needle.to_string() + &needle.to_string() + &needle.to_string();
}
if input.contains(needle_custom) {
println!("found needle {:?}", needle_custom);
}
}
return 1;
}
error[E0277]: expected a `std::ops::FnMut<(char,)>` closure, found `std::string::String`
--> src/lib.rs:13:18
|
13 | if input.contains(needle_custom) {
| ^^^^^^^^ expected an `FnMut<(char,)>` closure, found `std::string::String`
|
= help: the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`
= note: required because of the requirements on the impl of `std::str::pattern::Pattern<'_>` for `std::string::String`
如果我用needle_custom
替换"test"
,代码可以工作。
contains
方法将接受&str
或char
但不接受String
。
contains
方法is declared as
pub fn contains<'a, P>(&'a self, pat: P) -> bool
where
P: Pattern<'a>,
如果你看看implementors of Pattern
,你会看到它实现了char
和&str
。
这意味着您需要将&str
传递给contains
而不是您拥有的String
。因为&String
强迫&str
,这是一个很容易的变化:
-- if input.contains(needle_custom) {
++ if input.contains(&needle_custom) {