reverse an array in rust

To reverse an array in Rust, you can use a simple iteration approach, updating the values by swapping the elements at the beginning and the end of the array. Remember that arrays in Rust have a fixed size, so we need to use a mutable array for this task.

Here's an example implementation:

main.rs
fn reverse_array(arr: &mut [i32]) {
    let len = arr.len();
    for i in 0..len/2 {
        arr.swap(i, len-i-1);
    }
}
123 chars
7 lines

This function takes a mutable reference to an array of 32-bit integers (&mut [i32]) and iterates from the beginning to the middle of the array (len/2). For each iteration, the swap method updates the array by swapping the values at the current index i and its corresponding position from the end len-i-1.

You can call this function from your main code by simply passing the array as an argument:

main.rs
fn main() {
    let mut arr = [1, 2, 3, 4, 5];
    reverse_array(&mut arr);
    println!("{:?}", arr); // [5, 4, 3, 2, 1]
}
124 chars
6 lines

Note that we need to use mut to create a mutable binding for the array, as well as the reference to the array (&mut arr) to allow the function to modify its contents.

gistlibby LogSnag