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

Rust

Rust Problem Overview


The documentation says usize is

> Operations and constants for pointer-sized unsigned integers.

In most cases, I can replace usize with u32 and nothing happens. So I don't understand why we need two types which are so alike.

Rust Solutions


Solution 1 - Rust

As the documentation states usize is pointer-sized, thus its actual size depends on the architecture your are compiling your program for.

As an example, on a 32 bit x86 computer, usize = u32, while on x86_64 computers, usize = u64.

usize gives you the guarantee to be always big enough to hold any pointer or any offset in a data structure, while u32 can be too small on some architectures.

Solution 2 - Rust

Adding to @Levans' answer,

The size of usize is depended on how much size it takes to reference any location in memory.

on a 32 bit target usize is 4 bytes and on a 64 bit target usize is 8 bytes

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVaynView Question on Stackoverflow
Solution 1 - RustLevansView Answer on Stackoverflow
Solution 2 - RustAll Іѕ VаиітyView Answer on Stackoverflow