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.
usize is the type of Unsigned integers in rust; they meant to deal with integers in rust. Also, they allow positive integers only. we have several types available for unsigned integers, out of which usize is one of them, it stores the integer, or we can say its size in the form of an arch.
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.
u32 : The 32-bit unsigned integer type. u64 : The 64-bit unsigned integer type. usize : The pointer-sized unsigned integer type. f32 : The 32-bit floating point type. f64 : The 64-bit floating point type.
usize and isize have a size big enough to contain every address on the target platform. For example, on a 32 bit target, this is 4 bytes and on a 64 bit target, this is 8 bytes. Note that the phrasing doesn't exclude sizes other than 4 bytes or 8 bytes.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With