Multiple issues with HashSet


I have two problems, I would like the code from line 12 to 19 to work if possible by making the lifetime longer and I don't understand why line 14 is required, the code.
This problem is like this one and I would like to avoid taking ownership since input lives long enough.

Many thanks.

If you remove line 14 and replace 15 with

match set.get(&*a) {

the code works.

e: You can also do

match set.get::<str>(&a) {

The problem is that type inference isn't choosing the right get.

set.get(&a) doesn't work on its own because a is a String but you need to pass an &str.

In many cases, the compiler will automatically convert from &String to &str, but it doesn't happen here because HashSet::get can take multiple types, and the compiler won't try to guess which one to use. Instead, you can explicitly convert from String to &str, like:

match set.get(a.as_str())


match set.get(&a as &str)


OK, but why didn't the first version work, why is the lifetime wrong for that case? get isn't returning a reference with the lifetime of self (or set in this case).

I'm pretty sure it's because the return type of get has to implement Borrow<&'a str>, where 'a is the lifetime of a, and anything that implements that is bound by the 'a lifetime.

        let a: &str = &a;
        match set.get(&a) {

The argument here is &&str, so Q = &'a str for a temporary lifetime 'a. The set value is T = &str with a longer lifetime, but to satisfy T: Borrow<Q> the only possibility is impl<T> Borrow<T> for T. This is where the lifetime in Q and T don't meet up.

It works if you call set.get(a) instead, so the argument is &str with Q = str. Then this falls under impl<'_, T> Borrow<T> for &'_ T, where the lifetimes don't have to match. (Note that the set's T is this &'_ T -- sorry if that's too confusing...)

Further, all of this is only a problem because you're also trying to copy the &str into list, which is used after this temporary scope. Otherwise, lifetime variance would be fine to treat HashSet<&str> as having that shorter lifetime.

Thanks, I understand now.