Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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.

like image 218
Vayn Avatar asked Apr 12 '15 17:04

Vayn


People also ask

What does Usize mean in Rust?

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.

Why use usize?

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.

What is u32 rust?

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.

How big is usize?

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.


2 Answers

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.

like image 192
Levans Avatar answered Sep 26 '22 14:09

Levans


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

like image 37
All Іѕ Vаиітy Avatar answered Sep 22 '22 14:09

All Іѕ Vаиітy