"Doubling a vector" isn't something that's really done very often so there's no shortcut for it. In addition, it matters what is inside the Vec
because that changes what operations can be performed on it. In this specific example, the following code works:
let x = vec![1, 2, 3];
let y: Vec<_> = x.iter().cycle().take(x.len() * 2).collect();
println!("{:?}", y); //[1, 2, 3, 1, 2, 3]
The cycle()
method requires that the items in the Iterator
implement the Clone
trait so that the items can be duplicated. So if the items in your Vec
implement Clone
, then this will work. Since immutable references (&
) implement Clone
, a Vec<&Something>
will work but mutable references (&mut
) do not implement Clone
and thus a Vec<&mut Something>
will not work.
Note that even if a type does not implement Clone
, you can still clone references to that type:
struct Test;
fn test_if_clone<T: Clone>(_x: T) {}
fn main() {
let x = Test;
test_if_clone(x); //error[E0277]: the trait bound `Test: std::clone::Clone` is not satisfied
let y = &x;
test_if_clone(y); //ok
}
.clone()
s is necessary. – Widely