Best way to clone and append a single element?

I was previously using

let mut b = a.clone();

But I found the following makes a significant performance difference in my use case

let mut b = Vec::with_capacity(a.len() + 1);

I was wondering if there is an already existing method to clone and append a single element?

Probably not, because doing that repeatedly is a very inefficient way to build a vector. You might be interested in im — data structures in Rust //

Or, if you're just looking for a one-liner, you could do


That iterator will have an accurate size_hint, so won't need to reallocate the way that clone+push does.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.