Rust Array with Example


Rust Programming


Rust Programming


An array is a list of elements of the same type. For example, if we want to store the first five natural numbers, we can create an array instead of creating five different variables.

In Rust, we use the square brackets [] to create an array.

// array of natural numbers
let arr = [1, 2, 3, 4, 5];{codeBox}

Here, we have created an array named arr that has five numbers.

Creating an Array in Rust


In Rust, we can create an array in three different ways:

  • Array with data type
  • Array without data type
  • Array with default values

Let's understand each of these array creation methods in detail.


Array with Data Type in Rust

fn main() {
    // initialization of array with data type
    let numbers: [i32; 5] = [1, 2, 3, 4, 5];
    
    println!("Array of numbers = {:?}", numbers);
}{codeBox}


Output

Array of numbers = [1, 2, 3, 4, 5]{codeBox}


In the above example, we have created an array of numbers with the expression,

let numbers: [i32; 5] = [1, 2, 3, 4, 5];{codeBox}

Here,

  • numbers - name of the array
  • [i32; 5] - i32 is the predefined data type of array elements and 5 is the size of the array
  • [1, 2, 3, 4, 5] - elements inside the array


Array without Data Type in Rust


fn main() {
    // initialization of array without data type
    let numbers = [1, 2, 3, 4, 5];
    println!("array of numbers = {:?}", numbers);
}{codeBox}

Output

Array of numbers = [1, 2, 3, 4, 5]{codeBox}


In the above example, we have created an array of numbers with the expression,

let numbers = [1, 2, 3, 4, 5];{codeBox}

Here,

  • numbers - name of the array
  • [1, 2, 3, 4, 5] - element inside the array

You can see we have not defined the data type and size of the array. In this case, the Rust compiler automatically identifies the data type and size by looking at the array elements.


Array with Default Values in Rust


fn main() {
    // initialization of array with default values
    let numbers: [i32; 5] = [3; 5];
    println!("Array of numbers = {:?}", numbers);
}{codeBox}

Output

Array of numbers = [3, 3, 3, 3, 3]{codeBox}


In the above example, we have created an array of numbers with the expression,

let numbers: [i32; 5] = [3; 5];{codeBox}

Here,

  • numbers - name of the array
  • [i32; 5] - represents the data type (i32), and size (5) of the array
  • [3; 5] - is a repeat expression, here the value 3 will fill the array 5 times



Credits & Copyrights ©: Javatpoints, programiz & tutorialspoint


Post a Comment