laptou
laptou

Reputation: 7029

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?

Upvotes: 22

Views: 12615

Answers (3)

Anders Kaseorg
Anders Kaseorg

Reputation: 3875

You can build a Vec from as many pieces as you want using [T]::concat:

let x = [3, 4];
let y = [&[5], &x[..]].concat();
// gives vec![5, 3, 4]

Upvotes: 7

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

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

Upvotes: 14

ljedrz
ljedrz

Reputation: 22193

Rust's arrays have a fixed length, so there is no way of just combining them together; the usual way to achieve this result would be to have a mutable vector and to extend it with a slice:

fn main() {
    let x = [3, 4];
    let mut y = vec![5];
    y.extend_from_slice(&x);

    println!("{:?}", y); // [5, 3, 4]
}

Upvotes: 8

Related Questions