Create array like in python [x for x in range(10)]

Hi, dear rustations!
Is there concise way to create such an array, filled with range of numbers? So far I use Vec with for x in 0..10 loop for my purpose.

Rust doesn't have a list-comprehension , but you can use collect:

    let x: Vec<i32> = (0..10).collect();

If you want a slightly bigger expression, you'd use map.

    // Equivalent to [x * 2 for x in range(10)]
    let y: Vec<i32> = (0..10).map(|i| i * 2).collect();
2 Likes

Thank you very much, Gilnaa! But what about arrays? I would like to use arrays instead of Vec-s.

That's harder because when you create a range (like 0..10) its lower and upper bounds are determined at runtime, whereas the size of arrays must be known at compile time. It's worth mentioning Python does not have arrays, only the equivalent of Vecs. However, you can do something like this, even if it's not that concise:

let mut a = [0; 10];
for (i, v) in a.iter_mut().enumerate() {
    *v = i * 2;
}

That is the equivalent of [x * 2 for x in range(10)].

Also see array-init which allows you to do this:

let a: [_; 10] = array_init::from_iter((0..).map(|x| x * 2));
5 Likes

Thank you, Kestrer, for the speedy solution!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.