Rust vec extend vs append. In this Answer, we’ll discuss two methods, append() and extend(), to concatenate vectors in Rust. The “default” usage of this type as a queue is to use push_back to add to the queue, and pop_front to remove from the queue. Suppose we want to append to one slice with the elements in another. Jul 22, 2018 · The Vec::append method takes a mutable reference to the other vector because it removes the items from it. I think I have to override a Vec (don't know if this is possible in Rust) or code a Vec from source and include my own behaviour Oct 20, 2016 · You'll need to complete a few actions and gain 15 reputation points before being able to upvote. extend takes a value of any type that implements IntoIterator (which includes all iterator types) and extends the Vec by all elements returned from the iterator: vector. extend(it) Since extend belongs to the Extend trait, it also works for many other collection types. I use extend_from_slice for that, which works fine technically, see example code at the end. Vec A contiguous growable array type, written as Vec<T>, short for ‘vector’. It will make available only selected indexes. Jan 18, 2023 · The difference is append will move each item from one Vec to another, extend_from_slice will clone each item. In another Apr 10, 2021 · Note that Vec implements Extend<&T> if T: Clone T: Copy. iter() produces May 11, 2021 · This lint would suggest using the specialized Vec::append instead of vec. A place for all things related to the Rust programming language—an open-source systems language that emphasizes performance, reliability, and productivity. They allow you to store elements in a dynamically sized array. extend and append push onto the back in this manner, and iterating over VecDeque goes front to back. This article will thoroughly explain the best practices for vector concatenation in Rust, focusing on Ownership and Move Semantics. I always want to have a function that consumes a vector. The append method is ideal for merging vectors when you can afford to forget the source vector's contents, whereas the extend method helps when preserving the source vector is necessary. What's reputation and how do I get it? Instead, you can save this post to reference later. What's the idiomatic way to do that in Rust ? Many thanks ! A vector is a mutable data structure that stores elements of the same type in a contiguous block of memory. You can use Vec 's extend method. Upvoting indicates when questions and answers are useful. When extending a collection with an already existing key, that entry is updated or, in the case of collections that permit Jan 14, 2022 · There's Vec::append that modifies the vector in-place, and destroys its argument. Feb 24, 2015 · Is there any straightforward way to insert or replace multiple elements from &[T] and/or Vec<T> in the middle or at the beginning of a Vec in linear time? I could only find std::vec::Vec::insert, but that's only for inserting a single element in O(n) time, so I obviously cannot call that in a loop. PeekMut Experimental Structure wrapping a mutable reference to the last item in a Vec. After performing this operation, the first vector contains elements of the second vector at the end, and the second vector becomes empty. extend(bcd. Oct 11, 2025 · Have you ever wondered which method to use when combining one vector (Vec) with another in Rust? While it is possible to add elements using a simple loop, leveraging Rust's powerful features allows you to write safer and more efficient code. The question is: Is the code performant? To me it looks like internally this is resolved to an iterator which does a memcpy for each element. push (); can cause the entire Vec to reallocate anyway. A common task when working with vectors is to concatenate them, or in simpler terms, to merge them together. Jan 4, 2025 · Rust’s standard library offers several options, including Vec<T>, LinkedList<T>, and VecDeque<T>. So adding #[derive(Clone, Copy)] on Node will solve the issue Oct 11, 2014 · Take a look at the signature for extend: fn extend<I: Iterator<T>>(&mut self, iterator: I) Note that it takes self by a mutable reference, and that it doesn’t take a slice but rather an iterator (which is more general-purpose). The obvious way to do that is iterating over the second vector and use push on the first one to add each element of the second. Aug 1, 2019 · The difference between the functions is, that extend adds items one after another while, append adds all of them at once. You can append elements to a vector using the `push ()` method, the `append ()` method, the `extend ()` method, or the `insert ()` method. into_iter()); Or this: abc. This allows the destination data structure to decide how to add them efficiently. The end result would look like this, then: abc. Both are fast, but they fundamentally differ in how the original vector is handled after concatenation. The concatenation of these vectors helps us in combining and transforming data within Rust programs. extend() methods. append() and . There is also an append function that concat the second vector in the first one, but for unknown reason (to me) it empties the second one. Understanding the performance trade-offs between these can help you select the best fit for your applications. map(|&i| i)) (Bearing in mind that Vec. Splice A splicing iterator for Vec. drain(. Iterators produce a series of values, and collections can also be thought of as a series of values. Jan 12, 2019 · Yes, Andrey Tyukin, I had managed to confuse myself because in another spot of my code I had intentionally chosen append (which is like Python's extend). Jul 18, 2023 · append (): Fastest as it does not require new memory allocations but it leaves the appended vector empty. A method like foo. . Categories (optional) Kind: clippy::style What is the advantage of the recommended code over the original code Slightly more succinct code Potentially better perf? Helps raise awareness of append even existing :) Drawbacks None that I could Dec 22, 2023 · Well, I know about Extend and how to iterate over a vector. How to append to a vector in Rust Oct 21, 2022 · Expanding on my previous answer (I was on my phone), on line 3 here you're trying to assign the return value of append to final_order. Semantics and implementation of Vec::append I went down a rabbit hole trying to figure out what Vec::append actually means and why people say it is "efficient". Jun 14, 2024 · And it's not clear that appending directly to the Vec by value would perform better than that, because under normal circumstances any old vec. I'll happily accept the answer if Benjamin Lindley writes it up. A common example looks like this: vec. bar() can't return foo without also unconditionally destroying the foo Jan 7, 2025 · Rust: Concatenating Vectors with Append, Extend, and the + Operator (for Strings) In Rust, vectors are a powerful and flexible way to work with collections of items. The Extend trait bridges this gap, allowing you to extend a collection by including the contents of that iterator. In Rust we often act upon slices—even vectors or strings can be used as slices. append returns () but final_order is a Vec. Sep 14, 2025 · Extract If An iterator which uses a closure to determine if an element should be removed. Dec 9, 2016 · Hello, I'm trying to concatenate two vectors. extend (): Slower than append () since it has to reallocate the memory, but it leaves the original vectors intact. If you're after saving a line of code through methods returning the vector itself, you won't find them. This is because Rust has single ownership — a non-copyable object like Vec can exist in one place at a time, only. Sep 14, 2025 · Extend a collection with the contents of an iterator. Similarly, you can use extend to extend an existing collection (such as a Vec) with an iterator, rather than collecting the iterator into a Vec and then using append. I wrote a lot of Rust code, but I never needed this exact form of append. Rust provides several ways to do this: using the append Sep 28, 2024 · I have some piece of code which needs to add part of a vector to another vector. I keep reading people say that it is very efficient because it moves the values instead of copying, which is good for complex types that don't implement Copy. I could do a split_off at that index, extend the new elements into the left half of the split A double-ended queue implemented with a growable ring buffer. A VecDeque with a known list of items can be initialized from an array: Note that sometimes additional lifetimes are required on these return types, as this blog post explains. In Rust, vectors are implemented as dynamic arrays, which means that they can grow and shrink in size as needed. Dec 19, 2022 · Learn how to concatenate two vectors in Rust using the . append(&mut fn_returning_vec()); I would very much prefer to write vec. I was hoping it would do a memcpy for all elements at once, so instead of self Extend from slice. Into Iter An iterator that moves out of a vector. Example. My goal is to build a Struct which implements the expected behaviour: a kind of VecShadowIndexes. extend(other_vec. Mar 25, 2022 · When combining Vecs, I find myself flipping between Vec::append and Extend::extend without any clear motivated preference for one or the other. By choosing the right method, you can manage vector sizes with precision, whether you're adding pre-initialized elements, working with iterables, or optimizing with slices. Choosing the Jan 4, 2025 · Resizing vectors in Rust can be effectively handled by resize, extend, and extend_from_slice, depending on your needs. )). push_vec(fn_returning_vec()) instead. The append() method The append() method allows us to append the second vector to the first one. iter(). Oct 11, 2025 · The two main methods for efficiently combining vectors are append() and extend(). But since I'm new to Rust, I was lead down the wrong path by the compiler messages, and decided to post the question. If we look at Vec's implementation of Extend, we see: fn extend<I: IntoIte… Jan 7, 2025 · Rust offers a variety of robust methods for concatenating vectors and strings, each with their suitable context of application. lfbilstyh8dzvgsg8cllwmtgllqb81wt6mmrz5fdbtu