OneBite.Dev - Coding blog in a bite size

Merge Two Arrays In Rust

Code snippet for how to Merge Two Arrays In Rust with sample and detail explanation

Combining different data structures such as arrays is a tidy and efficient way of managing data. In this article, we are going to look at how two arrays can be merged in Rust programming language.

Merge Two Arrays Code Snippet

Let’s start with a simple code snippet for merging two arrays in Rust:

fn main() {
    let array1 = [1, 2, 3, 4, 5];
    let array2 = [6, 7, 8, 9, 10];

    let merged = [&array1[..], &array2[..]].concat();

    println!("{:?}", merged);
}

After running this code, we can expect an output that looks like the following:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Code Explanation for Merging Two Arrays

Firstly, we define our two arrays, array1 and array2:

let array1 = [1, 2, 3, 4, 5];
let array2 = [6, 7, 8, 9, 10];

Here, array1 and array2 are arrays of integers containing 5 elements each. The let keyword is used to create a variable binding, in this case, binding these collections of integers to array1 and array2 respectively.

The next part of the code is where the merging happens:

let merged = [&array1[..], &array2[..]].concat();

[&array1[..], &array2[..]] creates an array of references to the two input arrays. The processing of data in Rust can often require borrowing and referencing, especially when dealing with larger collections like arrays. The .. operator here is doing the slicing of the array to capture all elements.

Then, the concat() function is invoked on the array of arrays. This function is used to concatenate all elements in the array together, creating a new array to hold the result. The process creates a merge of the two input arrays.

Finally, the program prints the content of the merged array:

println!("{:?}", merged);

The println! macro is used here with the {:?} formatter, which helps to print the content of the merged array. The output shows the new merged array resulted from combining array1 and array2.

That’s how we can merge two arrays into a single array in Rust. This approach can be pretty handy when handling more complex programs where data manipulation is paramount. Happy coding!

rust