In this blog post, we will explore Array data structures of Rust.
Array is a fixed-length collection of elements from same data type.
To create & initialize array, it can be done in following different ways:
// Create & Initialize array with value 1 let i_arr: [i32; 5] = [1; 5]; // print array elements println!("{:?}", i_arr); PS D:\rust-samples\collections\array> cargo run [1, 1, 1, 1, 1]
Arrays can be initialized in this approach as well
// Create & initialize array with values let i_arr: [i32; 5] = [10, 20, 30, 40, 50]; // print array elements println!("{:?}", i_arr); PS D:\rust-samples\collections\array> cargo run [10, 20, 30, 40, 50]
Apart from the above 2 approaches, array can be created & initialized with default values at first and then at later stage it can be updated with different values. For this, it must be declared with mut
keyword to denote it as mutuable array.
// Create & Initialize array with default value 0 let mut i_arr: [i32; 5] = [0; 5]; // Update array element value i_arr[0] = 10; i_arr[1] = 20; i_arr[2] = 30; i_arr[3] = 40; i_arr[4] = 50; // print array elements println!("{:?}", i_arr); PS D:\rust-samples\collections\array> cargo run [10, 20, 30, 40, 50]
Built-in array functions
Length function
let i_arr: [i32; 5] = [0; 5]; println!("Length: {}", i_arr.len()); PS D:\rust-samples\collections\array> cargo run Length: 5
Iterating array
let i_arr: [i32; 5] = [1; 5]; // Array is not iterable println!("Iterating using IntoIterator implementation..."); // Warning: This works only if your array contains 32 or less elements // Iterating array for i in &i_arr { print!("{} ", i); } println!("\nIterating using .iter() function..."); // Iterating using .iter() method for i in i_arr.iter() { print!("{} ", i); } PS D:\rust-samples\collections\array> cargo run Iterating using IntoIterator implementation... 1 1 1 1 1 Iterating using .iter() function... 1 1 1 1 1
When your array has more than 32 elements, iterating using IntoIterator
implementation, will throw following error
--> src\main.rs:8:10 | 8 | for i in &i_arr { | ^^^^^^ the trait `std::iter::IntoIterator` is not implemented for `&[i32; 33]` |
Reverse Iteration
let i_arr: [i32; 5] = [10, 20, 30, 40, 50]; for i in i_arr.iter().rev() { print!("{} ", i); } PS D:\rust-samples\collections\array> cargo run 50 40 30 20 10
Swapping 2 elements
let mut i_arr: [i32; 5] = [10, 20, 30, 40, 50]; println!("Before swap: {:?}", i_arr); i_arr.swap(3, 4); println!("After swap: {:?}", i_arr); PS D:\rust-samples\collections\array> cargo run Before swap: [10, 20, 30, 40, 50] After swap: [10, 20, 30, 50, 40]
It will be panic when either of indice go out of bound
let mut i_arr: [i32; 5] = [10, 20, 30, 40, 50]; println!("Before swap: {:?}", i_arr); i_arr.swap(3, 5); println!("After swap: {:?}", i_arr); PS D:\rust-samples\collections\array> cargo run thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 5', C:\Users\Vinay\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\src\libcore\slice\mod.rs:512:35 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace error: process didn't exit successfully: `target\debug\array.exe` (exit code: 101)
Sort an array
let mut i_arr: [i32; 5] = [50, 40, 30, 20, 10]; println!("Before sorting: {:?}", i_arr); i_arr.sort(); println!("After sorting: {:?}", i_arr); PS D:\rust-samples\collections\array> cargo run Before sorting: [50, 40, 30, 20, 10] After sorting: [10, 20, 30, 40, 50]
Sorting array using custom comparator function
In case, if you would like to sort an array of String literals by using its length, you can use custom comparator function.
let mut s_arr = [String::from("C"), String::from("C++"), String::from("R"), String::from("Rust"), String::from("Java"), String::from("Python")]; println!("Before sorting: {:?}", s_arr); // Sorting by custom comparator function s_arr.sort_by(|a, b| a.len().cmp(&b.len())); println!("After sorting: {:?}", s_arr); PS D:\rust-samples\collections\array> cargo run Before sorting: ["C", "C++", "R", "Rust", "Java", "Python"] After sorting: ["C", "R", "C++", "Rust", "Java", "Python"]
Filter a collection
In case if you would like to filter out some items in your array, you can use starts_with(), ends_with() or contains() functions.
All these functions checks if the first element of slice has the character passed as argument. See below:
let s_arr = [String::from("C"), String::from("C++"), String::from("R"), String::from("Rust"), String::from("Java"), String::from("Python")]; println!("starts_with() C?: {}", s_arr.starts_with(&["C".to_string()])); println!("starts_with() J?: {}", s_arr.starts_with(&["J".to_string()])); println!("ends_with() a?: {}", s_arr.ends_with(&["a".to_string()])); println!("contains() t?: {}", s_arr.contains(&"n".to_string())); PS D:\rust-samples\collections\array> cargo run starts_with() C?: true starts_with() J?: false ends_with() a?: false contains() t?: false
Binary Search
In case if you have sorted array, you can use binary_search() function to search for a given element from array.
To use binary_search() on an array, it must be a sorted.
let s_arr = [String::from("C"), String::from("C++"), String::from("Java"), String::from("R"), String::from("Rust"), String::from("Python")]; match s_arr.binary_search(&"Java".to_string()) { Ok(value) => println!("Found the index {}", value), Err(e) => println!("Error!!! Most possible index where the value can be inserted... {}", e), } match s_arr.binary_search(&"Scala".to_string()) { Ok(value) => println!("Found the index {}", value), Err(e) => println!("Error!!! Most possible index where the value can be inserted... {}", e), } PS D:\rust-samples\collections\array> cargo run Found the index 2 Error!!! Most possible index where the value can be inserted... 6
Please kindly share your comments, if any.
Happy reading!!!
Top comments (0)