3

What is the simplest form of initializing an array with consecutive integers from 0 to N?

I have this code, but I think idiomatic Rust will look much simpler:

const NUM: u32 = 8;

fn main() {
    let mut int_list: [u32; NUM as usize] = [0; NUM as usize];
    for i in 0..NUM {
        int_list[i as usize] = i;
    }
    println!("data: {:?}", int_list);
}

playground

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Nulik
  • 6,748
  • 10
  • 60
  • 129
  • One of the duplicates [applied to your question](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=60b3e25ec0b0152f089aad42d456752e). – Shepmaster Jul 23 '19 at 16:54
  • 1
    @Shepmaster `arrayvec` is not part of main Rust source tree, so I don't want to use unofficial crates. – Nulik Jul 23 '19 at 17:04
  • 2
    *I don't want to use unofficial crates* — you are going to experience a lot of problems if you choose to keep this stance. Things that many people consider "core functionality" (like random number generation) are not part of the standard library. – Shepmaster Jul 23 '19 at 17:24
  • 1
    *Maybe someone would suggest to write a macro* — yes, they [already did](https://stackoverflow.com/a/36926695/155423). – Shepmaster Jul 23 '19 at 17:25
  • Your original question has no restriction about only using the standard library, but [I'd write it basically like your code](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=76eea11f5d17cccad9a65077bcb9f737). – Shepmaster Jul 23 '19 at 17:29
  • See also [Is there a way to count with macros?](https://stackoverflow.com/q/33751796/155423). – Shepmaster Jul 23 '19 at 17:32
  • Your question is totally answered by the duplicates, why should it be close as duplicates ? – Stargateur Jul 23 '19 at 17:50
  • 1
    `let int_list: Vec = (0..N).collect();` – BryceLarkin Dec 07 '22 at 02:20

0 Answers0