3 ms·
The methods on `String` should be a strict superset of the methods on `str` because `String` dereferences to `str`, thus `String` gets all of the `str` methods
by gamegoblin 6y ago
The methods on `String` should be a strict superset of the methods on `str` because `String` dereferences to `str`, thus `String` gets all of the `str` methods for free.
If you're familiar with say, `Vec<u8>` and `[u8]`, `String` and `str` are basically the same except they are contractually valid UTF bytes. So just like you can `push` and `extend` to a `Vec`, you can do the same to a `String`.
With regard to generic type parameters, if you want to code in Java or Go style, you can use dynamic dispatch trait objects to remove type parameters.
- brundolf 6y 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.
- aldanor 6y agoMaybe read a bit on Deref: https://doc.rust-lang.org/std/ops/trait.Deref.html https://doc.rust-lang.org/std/ops/trait.Deref.html Any time you have a &String reference, it triggers coercion to &str.
- Measter 6y agoUnfortunately 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" => (), _ => () }