Pearl: searching for `String` via `&str`

The following does not compile:

    let foo = vec!["hi".to_string()];

    if foo.contains("hi") {
        println!("yes");
    }

citing

    |
147 |     if foo.contains("hi") {
    |                     ^^^^ expected struct `String`, found `str`
    |
    = note: expected reference `&String`
               found reference `&'static str`

Assuming that in the real problem I have no control of the type of the Vec<String>, is it possible to search through structures (Vecs, Sets, HashMaps, etc.) via a &str, when the structure contains owned strings?

I know that I could just clone() the &str before lookup, but I'd rather not. Any ideas?

You can use the Iterator::any method like this:

if foo.iter().any(|x| x == "hi")
1 Like

Which in the case of Vec both this and contains are a linear search. iter() allocates an iterator but that can't be too bad.

Remember that this isn't an all-GC-all-the-time language. The iterator is just a struct on the stack, so "allocating" it is essentially free. Importantly it never needs to talk to the allocator -- there's no heap allocation or deallocation.

6 Likes