Answers to What are the differences between Rust's `String` and `str`? describe how &str
and String
relate to each other.
令人惊讶的是,str
比固定大小的数组更有限,因为它不能声明为局部变量.汇编
let arr_owned = [0u8; 32];
let arr_slice = &arr_owned;
let str_slice = "apple";
let str_owned = *str_slice;
在Rust 1.32.0中,我得到
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> src/lib.rs:6:9
这让人困惑,因为编译器可以知道"apple"
的大小,但它不是str
类型的一部分.
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?