I have a 2D vector that rejects indexing using i32
values, but works if I cast those values using as usize
:
#[derive(Clone)]
struct
Unlike Java, C# or even C++, numeric literals in Rust do not have a fixed type. The numeric type of a literal is usually inferred by the compiler, or explicitly stated using a suffix (0usize
, 0.0f64
, and so on). In that regard, the type of the 0
literal in assert_eq!(vec[0], 1);
is inferred to be a usize
, since Rust allows Vec
indexing by numbers of type usize
only.
As for the rationale behind using usize
as the indexing type: a usize
is equivalent to a word in the target architecture. Thus, a usize
can refer to the index/address of all possible memory locations for the computer the program is running on. Thus, the maximum possible length of a vector is the maximum possible value that can be contained in a isize
(isize::MAX == usize::MAX / 2
). Using usize
sizes and indices for a Vec
prevents the creation and usage of a vector larger than the available memory itself.
Furthermore, the usage of an unsigned integer just large enough to refer all possible memory locations allows the removal of two dynamic checks, one, the supplied size/index is non-negative (if isize
was used, this check would have to be implemented manually), and two, creating a vector or dereferencing a value of a vector will not cause the computer to run out of memory. However, the latter is guaranteed only when the type stored in the vector fits into one word.