bool 保证是 1 个字节吗?
Is bool guaranteed to be 1 byte?
Rust documentation 对 bool
的尺寸含糊不清。
它保证是 1 个字节,还是像 C++ 中那样未指定?
fn main() {
use std::mem;
println!("{}",mem::size_of::<bool>()); //always 1?
}
Rust 为 bool
向 LLVM 发出 i1
并依赖于它产生的任何东西。对于目前 Rust 支持的所有平台,LLVM 使用 i8
(一个字节)在内存中表示 i1
。另一方面,对于未来并不确定,因为到目前为止,Rust 开发人员一直拒绝承诺特定的 bool
表示。
因此,它由当前实现保证,但不受任何规范保证。
您可以在 this RFC discussion 以及链接的 PR 和问题中找到更多详细信息。
编辑:请参阅下面的答案,了解有关自此答案发布以来 Rust 中引入的更改的更多信息。
虽然历史上希望避免提交更具体的表示,但最终 decided in January 2018 bool
应该提供以下保证:
bool
的定义等同于_Bool
的C99定义
- 反过来,对于所有当前支持的平台,
bool
的大小正好是1。
文档已相应更新。在Rust reference中,bool
定义为:
The bool
type is a datatype which can be either true
or false
. The boolean type uses one byte of memory. [...]
从1.25.0开始也有记载,std::mem::size_of::<bool>()
的输出是1。
因此,确实可以依靠 bool
为 1 个字节(如果要对此进行更改,那将是一个非常大的更改)。
另请参阅:
- In C how much space does a bool (boolean) take up? Is it 1 bit, 1 byte or something else?
- Why is a boolean 1 byte and not 1 bit of size? (C++)
Rust documentation 对 bool
的尺寸含糊不清。
它保证是 1 个字节,还是像 C++ 中那样未指定?
fn main() {
use std::mem;
println!("{}",mem::size_of::<bool>()); //always 1?
}
Rust 为 bool
向 LLVM 发出 i1
并依赖于它产生的任何东西。对于目前 Rust 支持的所有平台,LLVM 使用 i8
(一个字节)在内存中表示 i1
。另一方面,对于未来并不确定,因为到目前为止,Rust 开发人员一直拒绝承诺特定的 bool
表示。
因此,它由当前实现保证,但不受任何规范保证。
您可以在 this RFC discussion 以及链接的 PR 和问题中找到更多详细信息。
编辑:请参阅下面的答案,了解有关自此答案发布以来 Rust 中引入的更改的更多信息。
虽然历史上希望避免提交更具体的表示,但最终 decided in January 2018 bool
应该提供以下保证:
bool
的定义等同于_Bool
的C99定义- 反过来,对于所有当前支持的平台,
bool
的大小正好是1。
- 反过来,对于所有当前支持的平台,
文档已相应更新。在Rust reference中,bool
定义为:
The
bool
type is a datatype which can be eithertrue
orfalse
. The boolean type uses one byte of memory. [...]
从1.25.0开始也有记载,std::mem::size_of::<bool>()
的输出是1。
因此,确实可以依靠 bool
为 1 个字节(如果要对此进行更改,那将是一个非常大的更改)。
另请参阅:
- In C how much space does a bool (boolean) take up? Is it 1 bit, 1 byte or something else?
- Why is a boolean 1 byte and not 1 bit of size? (C++)