`usize` 和 `u32` 有什么区别?

What's the difference between `usize` and `u32`?

文档说 usize

Operations and constants for pointer-sized unsigned integers.

在大多数情况下,我可以将 usize 替换为 u32 而不会发生任何事情。所以我不明白为什么我们需要两种如此相似的类型。

正如文档所述 usize 是指针大小的,因此它的实际大小取决于您编译程序所针对的体系结构。

例如,在 32 位 x86 计算机上,usize = u32,而在 x86_64 计算机上,usize = u64

usize 保证始终足够大以容纳数据结构中的任何指针或任何偏移量,而 u32 在某些体系结构上可能太小。

添加到@Levans 的回答,

usize 的大小取决于引用内存中任何位置所需的大小。

在 32 位目标上 usize 是 4 个字节,在 64 位目标上 usize 是 8 个字节