Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can isize and usize be different in rust?

Tags:

rust

Can isize and usize be different? Both of them can be used for memory size, index, offset.

Since usize is used for arrays why don't we just have usize

I am new to Rust so this might be a basic question.

Update: On a 32 bit system they are both 32 bit long and on a 64 bit system they are both 64 bit long. Irrespective of the sign.

like image 995
Damian Avatar asked Apr 04 '19 01:04

Damian


People also ask

How big is Usize in Rust?

This is what The Rust Reference has to say about 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.

What is Usize type 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.

What is i32 Rust?

i32 : The 32-bit signed integer type.


2 Answers

On a 32 bit system, isize is the same as i32 and usize is the same as u32. On a 64 bit system, isize is the same as i64 and usize is the same as u64.

  • usize cannot be negative and is generally used for memory addresses, positions, indices, lengths (or sizes!).
  • isize can be negative, and is generally used for offsets to addresses, positions, indices, or lengths.

In all currently supported architectures usize and isize are the same size as each other, but this may not always be the case! Novel instruction sets incorporating CHERI need to include metadata in pointers for tracking provenance. On 64 bit systems, this scheme requires an extra 64 bits for metadata, making pointers 128-bit, but pointer offsets can still be 64-bit.

There is some discussion about how CHERI support would affect Rust here.

like image 100
Peter Hall Avatar answered Oct 17 '22 16:10

Peter Hall


isize is architecture-based(e.g. 32bit/64bit) signed(negative/0/positive) integer type.

See here:

Primitive Type isize

The pointer-sized signed integer type.

See also the std::isize module.

The size of this primitive is how many bytes it takes to reference any location in memory. For example, on a 32 bit target, this is 4 bytes and on a 64 bit target, this is 8 bytes.

usize is architecture-based(e.g. 32bit/64bit) unsigned(0/positive) integer type.

See here:

Primitive Type usize

The pointer-sized unsigned integer type.

See also the std::usize module.

The size of this primitive is how many bytes it takes to reference any location in memory. For example, on a 32 bit target, this is 4 bytes and on a 64 bit target, this is 8 bytes.

like image 29
yellowB Avatar answered Oct 17 '22 16:10

yellowB