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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
needle_custom如果我替换为,该代码就可以工作"test"。
该contains方法将接受&str或 achar但不接受String。
该contains方法声明为
pub fn contains<'a, P>(&'a self, pat: P) -> bool
where
P: Pattern<'a>,
Run Code Online (Sandbox Code Playgroud)
如果您查看 的实现者Pattern,您会看到它是为char和实现的&str。
这意味着您需要传递&strtocontains而不是您拥有的String。因为&String强制 为&str,所以这是一个简单的更改:
-- if input.contains(needle_custom) {
++ if input.contains(&needle_custom) {
Run Code Online (Sandbox Code Playgroud)
这是您在 Playground 中进行的小更改的代码。
| 归档时间: |
|
| 查看次数: |
1978 次 |
| 最近记录: |