5 ms·
Because &str is just a string view. If you add vectors, you are adding owned types where you own the allocations. &str is not owned, but String is. We could ma
by Manishearth 10y ago
Because &str is just a string view. If you add vectors, you are adding owned types where you own the allocations. &str is not owned, but String is.
We could make the addition operator implicitly allocate here. It's a bit of a philosophical question if implicit allocations like that are desirable in rust. I lean towards being okay with the implicit allocation.
- pc2g4d 10y agoYou could maybe introduce a lint saying "possibly unnecessary allocation" when people `+` `&str`s together. Then beginners can still use the syntax that they're familiar with (and that basically every other language uses) but there's still notification somewhere that they can likely structure their code to be more efficient.
- Lev1a 10y agoIf I understand the ownership rules correctly, it would actually violate those rules to have the "familiar syntax". Also it seems to be Rust's thing to make things explicit, e.g. `.clone()`, not having `++`-style operators etc.
- steveklabnik 10y agoIn this case, due to the rules, it would be possible; the call to clone would be inside the method call, so you wouldn't see it. (With other signatures it may not, but Add returns a value, not a reference.) In other words, it would violate the conventions, but not the rules. (Okay so there's a _really_ obscure rule here that sill prevents this but it only matters because it's the standard library. It's not actually the signature)
- eximius 10y agoI would definitely side with it being okay. I like how string are modeled, but it doesn't mean it isn't painful sometimes. Making some common string operations like &str + &str defined but linted is a good balance of ergonomics and efficiency (that'd be a rare bottleneck, but the lint would make it visible).