OneBite.Dev - Coding blog in a bite size

Split An Array Into Smaller Arrays In Rust

Code snippet for how to Split An Array Into Smaller Arrays In Rust with sample and detail explanation

Rust, a systems programming language that focuses on performance and memory safety, incorporates powerful and unique features such as zero-cost abstractions, safe memory management, and prevention of data races. One of such features is the ability to split an array into smaller arrays, a handy method for manipulating and analyzing data.

Code Snippet for Splitting An Array into Smaller Arrays

Here’s a brief explanation of how you can split an array into smaller arrays using Rust programming language:

let array = [1, 2, 3, 4, 5, 6];
let chunk_size = 2;
let chunks: Vec<_> = array.chunks(chunk_size).collect();
println!("{:?}", chunks);

The code above will output:

[[1, 2], [3, 4], [5, 6]]

Code Explanation for Splitting An Array into Smaller Arrays

To start, we define an array of six elements:

let array = [1, 2, 3, 4, 5, 6];

Next, we declare the size of the smaller arrays we want to create:

let chunk_size = 2;

Then we use the chunks function from the slice, which returns an iterator over chunk_size elements at a time. The chunks are not overlapping. If chunk_size does not divide len evenly, then the last slice of the iteration will be shorter:

let chunks: Vec<_> = array.chunks(chunk_size).collect();

Finally, we print the resulting smaller arrays:

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

This will print:

[[1, 2], [3, 4], [5, 6]]

With the aforementioned code, we have successfully split the primary array into smaller arrays each containing two elements. This is a valuable tool for data manipulation and is indicative of Rust’s flexibility and efficiency.

rust