3
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`

The code works if I replace needle_custom with "test".

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
James Smith
  • 249
  • 1
  • 2
  • 8
  • Its kind of a bummer that the error message mentions `char` because it makes it harder to diagnose as a common `&str` vs `String` issue – turbulencetoo Feb 22 '19 at 21:49
  • In the future, you are encouraged to search for your exact error message. In many cases, this will directly lead you to existing questions and answers. – Shepmaster Feb 24 '19 at 19:35

1 Answers1

4

The contains method will accept an &str or a char but not a String.

The contains method is declared as

pub fn contains<'a, P>(&'a self, pat: P) -> bool 
where
    P: Pattern<'a>, 

And if you look at the implementors of Pattern, you'll see its implemented for char and for &str.

This means that you need to pass a &str to contains instead of your owned String. Because &String coerces to &str, this is an easy change:

-- if input.contains(needle_custom) {

++ if input.contains(&needle_custom) {

Here is your code with this small change working in the Playground.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
turbulencetoo
  • 3,447
  • 1
  • 27
  • 50