Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...