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

时间:2019-02-22 21:16:12

标签: string rust

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",该代码将起作用。

1 个答案:

答案 0 :(得分:1)

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在操场上工作。