Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Rust equivalent of JavaScript's spread operator for arrays?

In JavaScript, there is an operator called the spread operator that allows you to combine arrays very concisely.

let x = [3, 4];
let y = [5, ...x]; // y is [5, 3, 4]

Is there a way to do something like this in Rust?

like image 740
laptou Avatar asked Feb 03 '23 19:02

laptou


1 Answers

If you just need y to be iterable, you can do:

let x = [3,4];
let y = [5].iter().chain(&x);

If you need it to be indexable, then you'll want to collect it into a vector.

let y: Vec<_> = [5].iter().chain(&x).map(|&x|x).collect();
like image 183
Benjamin Lindley Avatar answered Feb 06 '23 16:02

Benjamin Lindley