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?
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?
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();
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]
}
x
or &x[..]
to the vector in the same line as vec![5]
, then do something with the result before assigning to y
? –
Sfax [T]
), so no new values can be appended through a slice. Dynamic manipulation of sequences is usually performed with vectors, so that they may own that memory. –
Churchly Add
between Vec<T>
and &[T]
, as it is already possible with String
and &[str]
, but it was rejected. –
Prepense Copy
(in my specific use case, I am trying to concatenate a Vec<u8>
with [u8; 2]
in a single line) I was hoping there might be a shortcut. –
Sfax Extend
is a suitable trait to use here once you already built a vector somewhere. –
Churchly 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]
© 2022 - 2024 — McMap. All rights reserved.