Sling Academy
Home/Rust/Rust: Concatenating vectors with append, extend, and the + operator (for strings)

Rust: Concatenating vectors with append, extend, and the + operator (for strings)

Last updated: January 07, 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. They allow you to store elements in a dynamically sized array. A common task when working with vectors is to concatenate them, or in simpler terms, to merge them together. Rust provides several ways to do this: using the append method, extend method, and the + operator when dealing with strings. This article will explore each approach with examples.

The append Method

The append method is used to move (i.e., transfer ownership of) elements from one vector to another in Rust. This operation results in the first vector receiving all elements of the second vector, and the second being drained of its contents.

fn main() {
    let mut vector1 = vec![1, 2, 3];
    let mut vector2 = vec![4, 5, 6];
    
    vector1.append(&mut vector2);
    
    println!("vector1: {:?}", vector1);
    println!("vector2: {:?}", vector2);
}

Output:

vector1: [1, 2, 3, 4, 5, 6]
vector2: []

As the output shows, vector2 is emptied after the append operation. This is a great way to combine vectors if you no longer need the original contents of the second vector.

The extend Method

The extend method is another way to concatenate vectors. Unlike append, this method borrows the data from one vector, which leaves the original one intact. It is more suitable if you wish to preserve the source vector.

fn main() {
    let mut vector1 = vec![1, 2, 3];
    let vector2 = vec![4, 5, 6];
    
    vector1.extend(&vector2);
    
    println!("vector1: {:?}", vector1);
    println!("vector2: {:?}", vector2);
}

Output:

vector1: [1, 2, 3, 4, 5, 6]
vector2: [4, 5, 6]

In this case, vector2 remains unaltered, making extend a non-destructive operation suitable for cases where you need both vectors afterward.

String Concatenation Using the + Operator

For strings, Rust provides a more intuitive way to concatenate them using the + operator. This operator can be used to concatenate Rust's String and &str types together.

fn main() {
    let string1 = String::from("Hello");
    let string2 = " World!";
    
    let result = string1 + string2;
    
    println!("{}", result);
}

Output:

Hello World!

The + operator takes ownership of the first operand (string1) while borrowing the second (string2), forming a new String. Remember, once + is used, the first String is no longer available for use, as demonstrated when you must not attempt to use string1 after this operation.

Conclusion

Rust offers a variety of robust methods for concatenating vectors and strings, each with their suitable context of application. 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. For strings, the + operator provides a straightforward approach to concatenation by efficiently re-using memory. Understanding these methods and when to use them can optimize and simplify your Rust programming phenomenal.

Next Article: Understanding indexing in Rust: Why Vec doesn’t allow negative indices

Previous Article: Rust - Mapping vector elements to new values with map, iter_mut, and collect

Series: Collections in Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior