<tutorialjinni.com/>

Arrays in Rust

Posted Under: Programming, Rust, Tutorials on Sep 29, 2021
Arrays in Rust
Array is collection of same type items. Arrays in Rust are different from other programming languages because they must contain a predetermined number of values. Arrays are meant to be fast as they are placed in stack and all indices of the array are contiguous in the memory. Unlike C, Rust provided a security feature by not letting the program access the memory index greater or less than the array's size.

Rust Array Definition

let primes = [2, 3, 5, 7]; // Array or Prime Numbers
let fruits = ["Apples","Oranges","Avocados"] // Array or fruits
By defautl all Rust arrays are immutable. To change the values mut identifier is requried. Array types can also be defined
let mut arr [i32; 5]= [9; 5];
above statment says, create a mutable array name arr, which will have i32 type 5 indicies (after = ) and initialize those 5 indicie with 9s in them. This statement is equal to let mut arr [i32; 5] = [9,9,9,9,9].

Rust Array Length

Length or size of array can be get form len() method.
fn main() {
    let fruits = ["Apples","Oranges","Avocados"];
    println!("Size of Array:{}",fruits.len());
}
// outputs: Size of Array:3

Rust iterate array

Rust provie iter() to traverse over each element of the array.
fn main() {
    let fruits = ["Apples","Oranges","Avocados"];
    for item in fruits.iter() {
            println!("{}", item);
    }
}

2D Array in Rust

Two dimensional or even multidimensional array is an array defined in another array. multidimensional arrays are define using [[]] square brackets in square brackets. Point to remember here is that internal square brackes are columns and external brackets are rows.
fn main() {
    let _2d_array:[[i32;3];3]  = [[0; 3]; 3];
    println!("{:?}", _2d_array);
}
// outputs [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
// because we initialize with zeros.
© Tutorial Jinni


imgae