|
|
|
|
|
by rspeer
3399 days ago
|
|
> String has a Deref instance for &str, so taking a reference to a String automatically works as a &str. You can also call .as_str().
>
> Going in the other direction, you can call .to_string() to make a copy of a &str as a new String. As a beginner in Rust myself, I would like to observe that &str vs. String problems come up all the time for me. Every one of them is quickly resolved by knowing where to add an & or a method call, it seems, and experts know when to do this, and they stop noticing the problem because it's only the beginners who are doing it wrong. But when every beginner is doing it wrong and every expert isn't, there is an ergonomics problem. |
|
I understand now, but initially it made absolutely no sense that String is a heap-allocated owned string and &str is a reference to a chunk of string data of known length stored somewhere that I probably don't have to care about.
It may be a teaching thing, but I do wonder if they could have been named better. I just don't really know what else you'd call them without them becoming overly verbose.