Answers to What are the differences between Rust's `String` and `str`? describe how &str
and String
relate to each other.
What is surprising is that a str
is more limited than a fixed-sized array, because it cannot be declared as a local variable. Compiling
let arr_owned = [0u8; 32];
let arr_slice = &arr_owned;
let str_slice = "apple";
let str_owned = *str_slice;
in Rust 1.32.0, I get
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> src/lib.rs:6:9
which is confusing, because the size of "apple"
can be known by the compiler, it is just not part of the str
type.
Is there a linguistic reason for the asymmetry between Vec<T>
<-> [T; N]
and String
<-> str
owned types? Could an str[N]
type, which would be a shortand to a [u8; N]
that only contains provably valid UTF-8 encoded strings, replace str
without breaking lots of existing code?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…