Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many elements can a Rust array have? [duplicate]

Tags:

rust

This code gave me an error:

fn main() {
    let x = [0 as u64; std::u64::MAX as usize];
    println!("Hello, world! {}", std::u64::MAX);
}
error: the type `[u64; 18446744073709551615]` is too big for the current architecture
 --> src/main.rs:2:9
  |
2 |     let x = [0 as u64; std::u64::MAX as usize];
  |         ^
like image 843
HelloWorld Avatar asked Nov 06 '19 14:11

HelloWorld


People also ask

What is duplicate elements in array?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

How do you find the size of an array in Rust?

The length of an array is the number of elements present in the array. We use the len() function to obtain this value.

How many elements are there in Rust?

Rust is a molecule that is composed of two elements: iron (Fe, atomic number 26) and oxygen (O, atomic number 8).

Do Rust arrays implement copy?

Arrays of any size implement the following traits if the element type allows it: Copy. Clone. Debug.


1 Answers

Array length is constrained by the isize type, which is a platform-sized integer:

The isize type is a signed integer type with the same number of bits as the platform's pointer type. The theoretical upper bound on object and array size is the maximum isize value. This ensures that isize can be used to calculate differences between pointers into an object or array and can address every byte within an object along with one byte past the end.

  • 16-bit platforms: A maximum value of 215 - 1
  • 32-bit platforms: A maximum value of 231 - 1
  • 64-bit platforms: A maximum value of 263 - 1
fn main() {
    let x = [(); std::isize::MAX];
    println!("Hello, world! {}", x.len());
}

Your specific error is because constructing an array of that many elements when the element has a non-zero size would require an outrageous amount of memory, more than a given platform would actually support.

An array's size is computed by the size of an element multiplied by the element count. Your array has elements of type u64 (8 bytes) and attempts to have 264 - 1 elements, totaling 147.6 exabytes.

On 64-bit Linux, with Rust 1.38, it appears that the maximum size is 247 - 1:

[0u8; (1usize << 47) - 1];
like image 185
Shepmaster Avatar answered Oct 23 '22 14:10

Shepmaster