w3resource

Rust Array Initialization & Slicing

Rust Vectors, Arrays, and Slices: Exercise-6 with Solution

Write a Rust program that creates an array of integers of size 8 and initializes it with values from 1 to 8. Slice the array to get a sub-array containing elements from index 2 to index 5 (inclusive). Print the sub-array.

Sample Solution:

Rust Code:

fn main() {
    // Declare an array of integers with size 8
    let array: [i32; 8] = [1, 2, 3, 4, 5, 6, 7, 8];

    // Slice the array to get a sub-array containing elements from index 2 to index 5 (inclusive)
    let sub_array = &array[2..=5];

    // Print the sub-array
    println!("Sub-Array: {:?}", sub_array);
}

Output:

Sub-Array: [3, 4, 5, 6]

Explanation:

Here is a brief explanation of the above Rust code:

  • fn main() { ... }: This line defines the main function, which is the entry point of the Rust program.
  • let array: [i32; 8] = [1, 2, 3, 4, 5, 6, 7, 8];: This line declares an array named 'array' of type [i32; 8] (array of integers with size 8) and initializes it with values from 1 to 8.
  • let sub_array = &array[2..=5];: This line slices the 'array' to get a sub-array containing elements from index 2 to index 5 (inclusive). The '&' symbol borrows a reference to the sub-array.
  • println!("Sub-Array: {:?}", sub_array);: Finally this line prints the sub-array to the console using debug formatting. The {:?} format specifier is used to print the elements of the array.

Rust Code Editor:

Previous: Rust Vector Mapping & Slicing.
Next: Rust Array Manipulation & Slicing.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.