arraysvectorrust

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?


Solution

  • 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();