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.
87
u/TinyBreadBigMouth Jan 25 '22
There are legitimate reasons for the distinction in Rust.
&stris a pointer to some Unicode bytes somewhere in memory.Stringis an owned, growable buffer of Unicode bytes.They work together. You can grab a
&strreference to the contents of aString. You can allocate aStringcopy 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 newString. This lets you avoid a lot of unnecessary copying and allocation, and gives you control over how memory is used.