HiveBrain v1.2.0
Get Started
← Back to all entries
gotcharustCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
andbetweenthedifferenceusizeu32what

Problem

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.

Solution

Warning: This answer is legacy for Rust, usize have been redefined as "can hold any memory location", see 95228 for very deep reasoning, TL;DR: a pointer is not just a number.

As the documentation states usize is pointer-sized, thus its actual size depends on the architecture you 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.

Context

Stack Overflow Q#29592256, score: 219

Revisions (0)

No revisions yet.