0

I'm trying to check if name contains file_name or if file_name contains name (playground):

use regex::Regex;

fn main() {
    let slashes = Regex::new(r"[\\\/]").unwrap();
    let name = String::from("firstname");
    let file_name = String::from("secondst/ring");
    let replaced_name = slashes.replace_all(&file_name, "_");
    if name.contains(&replaced_name) || replaced_name.contains(&name) {
        //TODO
    }
}

I get:

error[E0277]: expected a `Fn<(char,)>` closure, found `Cow<'_, str>`
   --> src/main.rs:8:22
    |
8   |     if name.contains(&replaced_name) || replaced_name.contains(&name) {
    |             -------- ^^^^^^^^^^^^^^ expected an `Fn<(char,)>` closure, found `Cow<'_, str>`
    |             |
    |             required by a bound introduced by this call
    |
    = help: the trait `Fn<(char,)>` is not implemented for `Cow<'_, str>`
    = note: required because of the requirements on the impl of `FnOnce<(char,)>` for `&Cow<'_, str>`
    = note: required because of the requirements on the impl of `Pattern<'_>` for `&Cow<'_, str>`
note: required by a bound in `core::str::<impl str>::contains`

I tried the following variants with no success:

if name.contains(file_name) || file_name.contains(name) {
if name.contains(&file_name) || file_name.contains(&name) {
if name.to_string().contains(&file_name) || file_name.to_string().contains(&name) {
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Sheki
  • 1,597
  • 1
  • 14
  • 25
  • Try `contains(&*name)`. This will do `Cow` -> `str` -> `&str`. – Shepmaster Mar 08 '22 at 15:31
  • Try: `name.contains(replaced_name.as_ref())` – Martin Gallagher Mar 08 '22 at 15:58
  • @MartinGallagher that doesn't even work on the playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=b7fc0a961ba7ca29635c8d31e4b7a199 – Sheki Mar 08 '22 at 16:18
  • @Shepmaster you changed the title of my question, then marked it as duplicate and in the duplicate message is saying: `Your post has been associated with a similar question. If this question doesn’t resolve your question, ask a new one.` well that was the reason why I asked a new question because the previous question doesn't answer and solve the problem! – Sheki Mar 08 '22 at 16:20
  • *doesn't answer and solve the problem* — sure it does: "This means that you need to pass a `&str` to `contains`". The only tweak is that you have a different path to get from `Cow` to `&str`, which is [what I commented](https://stackoverflow.com/questions/71397472/strcontains-fails-with-expected-an-fnchar-closure-found-cow-str#comment126198895_71397472) and have now added a second duplicate. – Shepmaster Mar 08 '22 at 16:45

0 Answers0