Is bool guaranteed to be 1 byte?

。_饼干妹妹 提交于 2019-12-22 01:25:58

问题


The Rust documentation is vague on bool's size.
Is it guaranteed to be 1 byte, or is it unspecified like in C++?

fn main() {
    use std::mem;
    println!("{}",mem::size_of::<bool>()); //always 1?
}

回答1:


Rust emits i1 to LLVM for bool and relies on whatever it produces. LLVM uses i8 (one byte) to represent i1 in memory for all the platforms supported by Rust for now. On the other hand, there's no certainty about the future, since the Rust developers have been refusing to commit to the particular bool representation so far.

So, it's guaranteed by the current implementation but not guaranteed by any specifications.

You can find more details in this RFC discussion and the linked PR and issue.




回答2:


While historically there was a wish to avoid committing to a more specific representation, it was eventually decided in January 2018 that bool should provide the following guarantees:

  • The definition of bool is equivalent to the C99 definition of Bool_
  • For all currently supported platforms, the size of bool is exactly 1.

The documentation has been updated accordingly. In the Rust reference, bool is defined as thus:

The bool type is a datatype which can be either true or false. The boolean type uses one byte of memory. [...]

It has also been documented since 1.25.0 that the output of std::mem::size_of::<bool>() is 1.

As such, one can indeed rely on bool being 1 byte (and if this is ever to change, it will be a pretty loud one).



来源:https://stackoverflow.com/questions/38047167/is-bool-guaranteed-to-be-1-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!