Hacker News new | ask | show | jobs
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.

3 comments

I think part of the problem might be that String and &str are not related in any intuitive way. My initial work in Rust was littered with what the heck is this, what's a str that there's a reference to, etc.

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.

I often joke that String -> StrBuf is my #1 wishlist item for a theoretical Rust 2.0.
I absolutely agree with you, and it seems worth looking closely at the problem to see if some change would make it easier to learn. However, the ownership and borrowing system represents the single biggest innovation and key idea of Rust, as well as the thing with the least ability to apply learnings from other languages. So while we should look closely at any roadblocks that make it harder to learn than necessary, we can't make it entirely transparent.
This is one reason why the new book focuses on teaching ownership and borrowing with String and &str. You're 10)% right.