6

This snippet of code:

fn main() {
    let s = "hello".to_string();
    let keywords = vec!["hello", "bye"];

    // if keywords.contains(&s.as_str())
    if keywords.contains(&&s)
    // ~> expected &&str, found &collections::string::String
    {
        println!("exists");
    }
}

normally, when function expect &str type, you can give a String

let s = "abc".to_string();
foo(&s); // ok,

however &&s doesn't deref to &&str, which I think is inconsistent.

Shepmaster
  • 274,917
  • 47
  • 731
  • 969
  • Also works: `keywords.contains(&&*s)` (`&*s` is the same as `s.as_str()`) – kennytm Apr 05 '16 at 14:08
  • 8
    Duplicate of [What are Rust's exact auto-dereferencing rules?](http://stackoverflow.com/q/28519997/155423). In short: It will deref as many times as possible (`&&String` -> `&String` -> `String` -> `str`) and then reference **at max once** (`str` -> `&str`). – Shepmaster Apr 05 '16 at 14:26
  • 2
    @shepmaster, after some reading in forums and RFC in details. I think this is not duplicate question of http://stackoverflow.com/questions/28519997/what-are-rusts-exact-auto-dereferencing-rules. It is about `deref coercions`. So the type `&&String` -> `&String` in that code because of coecions rules. – Gigih Aji Ibrahim Apr 12 '16 at 08:02

0 Answers0