149

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.

0

1 Answer 1

216

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.

6
  • 8
    Should I always use usize type for safety?
    – Vayn
    Commented Apr 12, 2015 at 17:49
  • 32
    Depends on what you want to do, if holding indexes in a memory structure, yes. For plain numbers, u32 is often good. The standard library always use usize when appropriate, and rust won't silently convert a u32 to a usize, so you'll see when they are needed.
    – Levans
    Commented Apr 12, 2015 at 17:53
  • 8
    u32 can also be too big if you're working on embedded systems, which Rust as a systems language is designed to work well with. If u32 was always too small, the language probably would've been designed to silently convert u32 into usize. Commented Oct 31, 2018 at 23:02
  • 8
    Note that usize might cause confusion in cases you are interested in deterministic behavior or serialisation. Commented May 15, 2019 at 0:45
  • @NicholasPipitone Probably not like u8 cannot be silently converted to u16. But it would've been provided into() and not just try_into(). Commented Aug 30, 2022 at 22:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.