Idiomatic copying/cloning of a vector in a parameterized function in Rust
Hello! I recently started learning Rust and encountered a problem when working with vectors in generic functions. I have a function that takes a vector and should return its copy with some modifications. But I can't figure out how to properly copy a vector inside a function when the element type is generic.
Here's an example that doesn't compile:
```rust
fn duplicate_vector(vec: Vec) -> Vec {
let mut new_vec = vec.clone(); // error: T does not implement Clone
new_vec.push(/* something */);
new_vec
}
```
The compiler complains that `T` does not implement the `Clone` trait. I understand that I need to add a `Clone` bound for type `T`, but this seems like an inflexible solution. What if I want to copy only certain elements or don't want to require `Clone` for t
No answers yet.
Log in to leave an answer
Blogs