gpt4 book ai didi

rust - 将 `bool` 转化为 `u8`

转载 作者:行者123 更新时间:2023-11-29 08:05:22 26 4
gpt4 key购买 nike

以下代码在 amd64 上与 Rust 1.8 一起正常工作。

use std::mem;

fn main() {
let f: u8 = unsafe { mem::transmute(false) };
let t: u8 = unsafe { mem::transmute(true) };
assert_eq!(0, f);
assert_eq!(1, t);
}

我的问题是,我可以假设这将始终有效吗?我试图找到有关 bool 表示的引用,但我只找到了 thisthis ,但我认为这并不权威。

最佳答案

截至 2021 年的更新:The Rust reference现在将 bool 的内存表示定义为等于 0 或 1 的 1 字节值:

An object with the boolean type has a size and alignment of 1 each. The value false has the bit pattern 0x00 and the value true has the bit pattern 0x01. It is undefined behavior for an object with the boolean type to have any other bit pattern.

关于rust - 将 `bool` 转化为 `u8`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36924530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com