Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a large array with a single value?

Tags:

rust

I am trying to implement Atkin's sieve in Rust. This requires initializing an array with false. The syntax for this on the internet no longer works.

fn main() {
    const limit:usize = 1000000000;
    let mut sieve:[bool; limit] = [false];
}

I expect this to create an array of size limit filled with false, instead

rustc "expected an array with a fixed size of 1000000000 elements, found one with 1 element".

like image 410
AnnoyinC Avatar asked Nov 16 '25 07:11

AnnoyinC


1 Answers

[false] is an array with one element, i.e., its type is [bool; 1].

What you want is [false; limit] instead of [false]:

fn main() {
    const limit: usize = 1_000_000_000;
    let mut sieve = [false; limit];
}

There is no need for the type annotation [bool; limit] here as it can be inferred.

like image 56
ネロク・ゴ Avatar answered Nov 17 '25 20:11

ネロク・ゴ