3 ms·
I wrote a blog post that may help you! https://steveklabnik.com/writing/when-should-i-use-string-vs-str/ https://steveklabnik.com/writing/when-should-i-use-stri
by steveklabnik 2y ago
I wrote a blog post that may help you! https://steveklabnik.com/writing/when-should-i-use-string-vs-str/ https://steveklabnik.com/writing/when-should-i-use-string-vs...
If you want to understand more deeply, the Rust Programming Langauge, chapter 4, uses String and &String and &str to talk about ownership and borrowing. Here’s a link to the start of that chapter: https://doc.rust-lang.org/stable/book/ch04-00-understanding-ownership.html https://doc.rust-lang.org/stable/book/ch04-00-understanding-...
- ryandrake 2y agoHow timely and helpful, thanks! Your blog post is practical and clearly explains what to do, when, which is helpful. What's confusing is why Rust has the two types and why the language designers decided it was a good idea to have to convert back and forth between them depending on whether it was going in a struct or being passed as an argument. I suppose the "why" is probably better found in the Rust docs. As a long-time C++ user, it seems like std::string vs const char* all over again, and we somehow didn't find a better way.
- steveklabnik 2y agoYep, that’s exactly it: I wanted to focus purely on what to do, rather than weigh it down with what’s already in the Rust book. It’s closer to std::string and std::string_view. But yes, in a language with value and reference semantics, when you also care about performance, you just can’t do any better: you need both types. Or at least, if you want the additional correctness guarantees and safety provided by communicating ownership semantics in the type. C gets away with just char * but then you have to read the docs to figure out what you’re allowed to do with it and what your responsibilities are.
- AlotOfReading 2y agoIn C++ terms, String is std::string, &str is std::string_view. They're different things, but they can appear similar.
- brabel 2y agoA Rust `String` reference (i.e. &String) can always be passed where `&str` is expected because `String` has a `Deref<Target=str>` impl... in that sense they don't just appear similar, they are polymorphic.
- School-Cotton 2y agoRust has two different types because they are fundamentally different things, just like `std::string` and `const char *` are! A pointer to some memory is not the same thing as a struct that has a pointer to memory, as well as a capacity field and the ability to resize itself.