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.rs123 chars7 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.rs124 chars6 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