OneBite.Dev - Coding blog in a bite size

Extract A Sub-Array From An Array In Rust

Code snippet for how to Extract A Sub-Array From An Array In Rust with sample and detail explanation

Working with arrays is integral to any programming language, and Rust is no different. In this simple guide, we will focus on how to extract a sub-array from an array in Rust programming language.

Code snippet for Extracting a Sub-Array From an Array in Rust

fn main() {
    let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    let sub_arr = &arr[3..6];
    println!("{:?}", sub_arr);
}

Code Explanation for Extracting a Sub-Array From an Array in Rust

Step by step, let’s break down the above Rust code snippet to better understand how it works:

  1. Defining the array: Here, we initialize our main array arr that contains integers ranging from 1 to 10.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  1. Extracting the sub-array: This is where we extract a sub-array from the initial array. In Rust, we can do this by using range indexing. The syntax &arr[3..6] command will extract elements from index 3 up to, but not including, index 6.
let sub_arr = &arr[3..6];
  1. Printing the sub-array: Lastly, using the println! macro, we print out our new sub-array for confirmation. The {:?} inside the string is a placeholder for a value that will be stringified. In this case, it’s the entire sub_arr.
println!("{:?}", sub_arr);

When you run this code, the output will be [4, 5, 6], which corresponds to the 4th, 5th, and 6th elements of our original arr.

And that’s it! You’ve successfully extracted a sub-array from an array in Rust. It’s quite simple once you get the hang of the range indexing syntax. Learn and explore more about Rust programming with practical code snippets and explanations.

rust