8 ms·
> Well, &String is ALSO a valid Rust type Yeah I know. This is really confusing when learning rust. Coming from another language where there's a single rust ty
by josephg 6y ago
> Well, &String is ALSO a valid Rust type
Yeah I know. This is really confusing when learning rust. Coming from another language where there's a single rust type its really tricky to figure out when to use what!
For reference, I now use String for large strings, string builders, and when the string is owned - like in a struct. And &str when taking in a string as an argument to a function. Or when iterating or something like that where you don't want to move the string. And then for small owned strings (like labels or IDs) I reach for the InlinableString crate. That handles small strings inline and puts large strings on the heap, like what Apple does for Swift and Objective-C.
I understand why its this way; but its a pity the best answer rust has is so complex and confusing.
- deleted 6y ago[deleted]
- brundolf 6y agoIt's worth noting that you can use &String anywhere that &str is accepted. The distinction is subtle and I agree it's sort of confusing, but in practice the former gets automatically coerced to the latter as needed