当提供的输入是字符串引用时,str :: contains不起作用[复制]

问题描述 投票:0回答:1
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",代码可以工作。

string rust
1个回答
2
投票

contains方法将接受&strchar但不接受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) {

Here is your code with this small change在游乐场工作。

© www.soinside.com 2019 - 2024. All rights reserved.