rust - Rust 中的 usize/isize 类型是否保证始终为 32 位或 64 位?
问题描述
如果我编译一个针对 16 位架构的程序,将std::mem::size_of::<usize>()
返回 2,还是保证(通过规范、RFC 或其他方式)总是返回 4 或 8?
解决方案
这就是Rust 参考要说的usize
:
usize
并且isize
具有足够大的大小以包含目标平台上的每个地址。例如,在 32 位目标上,这是 4 个字节,而在 64 位目标上,这是 8 个字节。
请注意,措辞不排除 4 字节或 8 字节以外的大小。事实上,Rust 已经支持16 位平台usize
:msp430-none-elf
(MSP430 是一个 16 位微控制器)。
如果要根据指针的大小进行条件编译,可以使用target_pointer_width
配置选项。这是库中的示例用法core
:
#[cfg(target_pointer_width = "16")]
#[lang = "usize"]
impl usize {
uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
"[0x34, 0x12]", "[0x12, 0x34]",
usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
}
#[cfg(target_pointer_width = "32")]
#[lang = "usize"]
impl usize {
uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
"0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
}
#[cfg(target_pointer_width = "64")]
#[lang = "usize"]
impl usize {
uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
"0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
"[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
"[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
}
推荐阅读
- excel - 使用批处理文件或 Excel 表创建由数字和字母组成的一系列值
- javascript - Vue.js - 在 Vuex 模块中获取当前路由
- c# - REST 不适用于已发布版本,可在本地工作
- android - android,在没有上下文或生命周期对象的情况下如何处置观察者
- google-apps-script - Google表格,从返回表格的函数中获取单个值
- node.js - Mongoose js - pushAll、concat 数组
- kotlin - 活动和片段问题中的导航控制器
- google-cloud-platform - 使用 Google Cloud DNS 记录中的“at-sign”
- reactjs - 使用 this.props.children() 和 React.cloneElement 进行渲染时,如何将 Parent 道具传递给 Children?
- javascript - 减少数组函数上的打字稿错误-“字符串”不可分配给类型参数