OneBite.Dev - Coding blog in a bite size

Reverse Arrays Items In Rust

Code snippet for how to Reverse Arrays Items In Rust with sample and detail explanation

In this article, we will learn how to reverse array items in Rust, a popular systems programming language. It is a crucial skill in array manipulation and can come in handy when sorting or organizing data.

Code Snippet: Reverse Array Items in Rust

fn main() {
    let mut array = [1, 2, 3, 4, 5];
    println!("Original array: {:?}", array);

    array.reverse();

    println!("Reversed array: {:?}", array);
}

Code Explanation for: Reverse Array Items in Rust

Let’s take it step by step:

  1. fn main(): This is the main function where our program begins execution.

  2. let mut array = [1, 2, 3, 4, 5];: We’re creating a mutable array of integers.

  3. println!("Original array: {:?}", array);: Here we’re printing out the original array using the debug print ({:?}), which is a placeholder for our array variable.

  4. array.reverse();: This is where the magic happens. We’re calling the reverse method on our array, which will reverse the order of the elements in place. This method doesn’t return anything, instead, it changes the actual array.

  5. println!("Reversed array: {:?}", array);: After the previous line has executed and reversed our array, we then print out the array after the reversal.

And that’s it! By simply using the built-in reverse method available in Rust, we can easily reverse the order of elements in an array. Remember that this function works in-place and does not return a new array. This is different from some other languages where reversing an array results in a new array and leaves the original array unchanged.

rust