Arrays - Access Last Element


#1

After a developer writes a program that declares and instantiates an Array with a “fixed length” of 4 (running rustc 1.0.0-nightly) and then builds it without receiving any warnings or errors with Cargo.

let arr_imm = [1, 2, 3, 4];
println!("last element of arr_imm is: {}", arr_imm[-1]);

Why is it that when they then run the executable program (which contains code that attempts to access element number -1 of a Rust Array) does it think it should access the Array’s index number of 18446744073709551615 (even though the Rust Array has been pre-declared with a “fixed length” of 4) and give the following error when the executable is run?

error when the Rust file is run: thread '<main>' panicked at 'index out of bounds: the len is 4 but the index is 18446744073709551615' 

The integer literal 18446744073709551615 is equivalent to 2^64-1, so this outcome appears to indicate that despite the executable already knowing that an Array only has a “fixed length” of 4, it will ignore this and interpret that it should always attempt to access element 18446744073709551615 for an expression requesting access to element number -1.

Does this integer literal 18446744073709551615 represent the maximum possible “length” of a Rust Array, where the “length” is of 64 bit unsigned integer literal data type?


#2

I’m not sure why, but this just looks like an overflow problem of a -1 unsigned int overflowing.

I would definitely be interested in the thought behind not interpreting a -1 value at compile-time.


#3

Maybe the data type for the “length” of a Rust Array is the std::u64 Module of the The Rust Standard Library


#4

Slices use usize for indices. That is a platform dependent integer and on 64 bit it is a 64 bit integer.
The integer overflow is wanted because runtime checks are too expensive and -1 it is even used in the standardlibrary for defining Int::max_value(), although I am surprised that the conversion is implicit even without a lint.
Also lints for out of bound errors at compiletime would be nice.


#5

I thought debug compilations had overflow runtime checks. Shouldn’t it have?