Why can fixed-size arrays be on the stack, but str cannot?
asymmetry between
Vec<T>
<->[T; N]
andString
<->str
That's because you confused something here. The relationships are rather like this:
Vec<T>
⇔[T]
String
⇔str
In all those four types, the length information is stored at runtime, not compile time. Fixed size arrays ([T; N]
) are different in that regard: they store the length at compile time, but not runtime!
And indeed, both [T]
and str
can't be stored on the stack, because they are both unsized.
Could an
str[N]
type, which would be a shorthand to a[u8; N]
that only contains provably valid UTF-8 encoded strings, replacestr
without breaking lots of existing code?
It wouldn't replace str
, but it could be an interesting addition indeed! But there are probably reasons why it doesn't exist yet, e.g. because the length of a Unicode string is usually not really relevant. In particular, it usually doesn't make sense to "take a Unicode string with exactly three bytes".
[T]
andstr
can't be stored on the stack, because they are both unsized
While this is true today, it may not be true in the future. RFC 1909 introduces unsized rvalues. One of the powers that this feature would give is variable-length arrays:
The RFC also describes an extension to the array literal syntax:
[e; dyn n]
. In the syntax,n
isn't necessarily a constant expression. The array is dynamically allocated on the stack
No mention is made of whether a string will be directly possible, but one could always create a stack-allocated array of bytes to be used as storage for a string.