Trying and failing to create a lazy static FnvHashSet<&'static str>


#1

I have some function sort of like this:

fn f(word: &mut String) { // In the real function I call word.clear() in some cases
    let w = word.clone();
    if DATATYPES.contains(&w) { // ERROR
        println!("Yes");
    }
}

And rustc gives me this error:

the trait `std::borrow::Borrow<&mut std::string::String>` is not
implemented for `&str`

The lazy static code is here:

static ref DATATYPES: FnvHashSet<&'static str> = {
    let mut m: FnvHashSet<&'static str> = FnvHashSet::default();
    for datatype in ["bool", "bytearray", "bytes", "complex", "dict",
                     "float", "frozenset", "int", "list", "memoryview",
                     "object", "set", "str", "tuple", "self",].iter() {
        m.insert(datatype);
    }
    m
};

At the moment I’ve worked around it by using FnvHashSet<String> and m.insert(datatype.to_string()); but that seems wasteful.

I did try rustc --explain E0277 but find that one too general to help. (However, I have started to use this facility and it does sometimes give me the clue I need.)


#2

You just need to deref to a slice:

if DATATYPES.contains(&*w) // note the *

Deref coercion does not take place in generic contexts, so contains() won’t do it automatically for you.


#3

Thank you @vitalyd that works perfectly!