首页 > 解决方案 > Rust 中的 usize/isize 类型是否保证始终为 32 位或 64 位?

问题描述

如果我编译一个针对 16 位架构的程序,将std::mem::size_of::<usize>()返回 2,还是保证(通过规范、RFC 或其他方式)总是返回 4 或 8?

标签: rust

解决方案


这就是Rust 参考要说的usize

usize并且isize具有足够大的大小以包含目标平台上的每个地址。例如,在 32 位目标上,这是 4 个字节,而在 64 位目标上,这是 8 个字节。

请注意,措辞不排除 4 字节或 8 字节以外的大小。事实上,Rust 已经支持16 位平台usizemsp430-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!() }
}

推荐阅读