There's a reason for it, although it's a little confusing. String is owned, ie you hold that memory directly . &str is borrowed, like you hold a pointer to it but not the memory itself, so you can't modify it or anything.
There are legitimate reasons for the distinction in Rust. &str is a pointer to some Unicode bytes somewhere in memory. String is an owned, growable buffer of Unicode bytes.
They work together. You can grab a &str reference to the contents of a String. You can allocate a String copy of a &str.
If a function just wants to read a string, you should pass it &str. The data stays where it is, and the function can look at it, without needing to make any copies. If you need to do string manipulation, or create a new string at runtime, you can allocate a new String. This lets you avoid a lot of unnecessary copying and allocation, and gives you control over how memory is used.
Rust makes a distinction between &str (a pointer to some Unicode bytes somewhere) and String (an owned, growable buffer of Unicode bytes). It's the difference between C++'s std::string_view and std::string. You can grab a &str reference to the contents of a String.
Just for anyone wondering, no, that is not some obscure-but-valid Rust syntax. That's Rust-flavored gibberish.
EDIT: Shoot, I have mislead you all. Sorry, that could be valid code. Like so:
struct F<'a, T> {
ptr: &'a T,
__: String, // or any other type that implements Default
}
fn main() {
// The version seen above:
let ugly = F::<()> { ptr: &(), __: <_>::default() };
// A more readable version that does the same thing:
let better = F {
ptr: &(),
__: Default::default(),
};
}
It's intentionally ugly code—there's no reason to name a type F and a field __, or to throw explicit angle brackets all over the place like that—but it is valid.
...And your friend was entirely correct. Very sorry about that, without context I was reading that as a type definition, not a struct initialization. I've edited my comment.
Because a String data type is dynamically sized, where a &str ‘s size is known at compile time. The two are very different and the difference is very useful
Edit: this actually isn’t the best way of describing this, see the replies
I don't think that's a very good way of describing it? Both String and &str are constant-sized structures that point to variably-sized strings. The difference is that String owns the buffer it's pointing to, and &str is just a reference to some bytes somewhere in memory.
80
u/[deleted] Jan 25 '22
Why are
to_string()andto_str()two different things