DEV Community

Sivakumar
Sivakumar

Posted on • Edited on

Rust Data Structures: array

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

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]`
  |
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
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]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode
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]
Enter fullscreen mode Exit fullscreen mode
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"]
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

Please kindly share your comments, if any.

Happy reading!!!

Top comments (0)