3 ms·
&String cannot, by itself, handle a substring because it has to point to an (immutable) whole String struct in memory. Any extra syntax or types to package up s
by dbaupp 6y ago
&String cannot, by itself, handle a substring because it has to point to an (immutable) whole String struct in memory. Any extra syntax or types to package up subslice boundaries would almost certainly end up as something similar to &str, just with potentially different syntax and likely slower.
- Misdicorl 6y agoI think you are incorrect. Exposing a slice of a String as an &String should have no performance impact (pointer and length just like &str). The only thing that becomes interesting is whether you can expose a mutable string slice
- dbaupp 6y agoAt the very least, retrieving data from a &String will involve two pointer lookups (one for the &, one for the internal pointer in the String) whereas plain String and &str involve just one. In addition, since the String object itself cannot be mutated, a slice like s[10:20] as a &String requires storing the 10 and 20 outside the String and then doing pointer offsets when reading the data. A &str does not need to do this, because the pointer offset happens on creation. Because of this, the &str is also smaller (and this is more efficient because of caches), because it only needs to store a pointer and length (16 bytes, on typical machines), while a &String needs to store at least a pointer to the String and the start/end indices (24 bytes). One could have various special cases to make &String “work” but it likely ends up being equivalent to &str. The key piece in mind: if one retains the &String name, it makes the language less orthogonal, with more special cases, because taking a reference to a string variable like &s to get a value of type &String behaves very differently to taking a reference to any others like &some_int (of type &i32), which will cause problems in generic code.
- Misdicorl 6y agoWhat issues arise by aliasing &str and &String to the same (&str) implementation? Does any code actually rely on &String pointing at the String itself rather than the bytes of the string? Perhaps its more strange/broken to special case &String that it is to have the (imo) warty &str.
- dbaupp 6y agoUnsafe generic code likely cares, where it is coercing a &T to a *const T and then relying on pointer stability/consistency. It will also cause difficulties with methods like ‘.capacity()’, because that info is lost with &str.