How to swap two values of an array in Rust

1 Answer

0 votes
#![allow(non_snake_case)]

fn swap_values(array: &mut [isize], index1: usize, index2: usize) {
    let temp = array[index1];
    array[index1] = array[index2];
    array[index2] = temp;
}
    
fn main()
{
    let mut arr = [99, 3, 7, 0, 2, 1, 8, 6];

    swap_values(&mut arr, 0, 4);
    
    {
        let mut i : usize = 0;
        while i < arr.len() {
            print!("{} ", arr[i as usize]);
            i += 1;
        }
    }
}




/*
run:

2 3 7 0 99 1 8 6 

*/


 



answered Apr 20, 2023 by avibootz
...