为什么固定大小的数组可以放在堆栈上,而str却不能呢? [英] Why can fixed-size arrays be on the stack, but str cannot?
问题描述
回答 Rust的`String`有什么区别?和`str`?描述&str
和String
如何相互关联.
Answers to What are the differences between Rust's `String` and `str`? describe how &str
and String
relate to each other.
令人惊讶的是,与固定大小的数组相比,str
的局限性更大,因为它不能声明为局部变量.编译
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;
在Rust 1.32.0中,我得到了
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
令人困惑,因为编译器可以知道"apple"
的大小,因此它不是str
类型的一部分.
which is confusing, because the size of "apple"
can be known by the compiler, it is just not part of the str
type.
在Vec<T>
<-> [T; N]
和String
<-> str
所拥有的类型之间存在不对称性的语言原因吗? str[N]
类型(仅包含经证明有效的UTF-8编码字符串的[u8; N]
类型的缩写)可以代替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?
推荐答案
Vec<T>
<->[T; N]
和String
<-str
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
Vec<T>
⇔[T]
String
⇔str
在所有这四种类型中,长度信息是在运行时而不是编译时存储的.固定大小的数组([T; N]
)在这方面有所不同:它们在编译时存储长度,而不在运行时存储长度!
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!
实际上,[T]
和str
都不能存储在堆栈中,因为它们都没有大小.
And indeed, both [T]
and str
can't be stored on the stack, because they are both unsized.
str[N]
类型(仅包含经证明有效的UTF-8编码字符串的[u8; N]
的简写形式)是否可以替换str
而又不破坏大量现有代码?
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?
它不会替代str
,但确实是一个有趣的补充!但是,可能有一些原因导致它尚不存在,例如因为
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".
这篇关于为什么固定大小的数组可以放在堆栈上,而str却不能呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!