Hacker News new | ask | show | jobs
by brundolf 2000 days ago
> The methods on `String` should be a strict superset of the methods on `str` because `String` dereferences to `str`

I've found that sometimes this doesn't happen automatically (at least when passing as an argument; maybe not when calling methods). i.e., you have to explicitly call .as_str() in some situations. Even as someone who's comfortable with the String/&str distinction and moderately familiar with Rust, it's not clear to me where this is and isn't necessary. The compiler just tells me when I make the wrong guess.

1 comments

Maybe read a bit on Deref: https://doc.rust-lang.org/std/ops/trait.Deref.html

Any time you have a &String reference, it triggers coercion to &str.

Unfortunately that is not always the case. This fails to compile, for example (and is fairly irritating):

    let my_str = "Hello".to_owned();
    match &my_str {
        "Hello" => (),
        _ => ()
    }
try &*my_str
Yes, that's the trivial "fix" to make it work, but that's not my point. In most other similar situations the compiler does that for me, but not here. It feels like something the compiler should be doing, not me.