Idiomatic way to extend/construct a vector

What is the most idiomatic way to write the following piece of code preferably in one line? Sorry, I am learning Rust. I'd really appreciate your help.

let mut ret:Vec<i32> = (-(n-1)/2..=-1).collect();
ret.push(0);
ret.extend(1..=(n-1)/2);

Sample vector contents as a result for n=5:

[-2, -1, 0, 1, 2]

This may actually be more efficient than the "idiomatic" way in this case. But either way, here it is:

let ret = (1..n * 2).map(|x| x - n).collect::<Vec<_>>();

Playground

Ack! Wait, I misread your question, n = 5 in your example, which is not what my program would produce. I will update shortly with a solution.


Adding n = (n + 1) / 2; before that makes my original solution work.
Playground

I'd rather spend more time on it but I cannot at the moment.

1 Like

Thank you. I get the idea. This works for me:

let ret = (-n/2..=n/2).map(|x| x).collect::<Vec<_>>();
1 Like

That .map(|x| x) does nothing, so you can remove it.

4 Likes