In Rust, you can shuffle an array using the rand crate's Fisher-Yates shuffle algorithm.
In this example,
intArray
containing integers.intArray
.extern crate rand;
use rand::seq::SliceRandom;
fn main() {
let mut int_array = [1, 2, 3, 4, 5];
let mut rng = rand::thread_rng();
int_array.shuffle(&mut rng);
println!("Shuffled Array: {:?}", int_array);
}
Shuffled Array: [3, 4, 1, 5, 2]
In this example,
str_array
containing strings.str_array
.extern crate rand;
use rand::seq::SliceRandom;
fn main() {
let mut str_array = ["apple", "banana", "cherry"];
let mut rng = rand::thread_rng();
str_array.shuffle(&mut rng);
println!("Shuffled Array: {:?}", str_array);
}
Shuffled Array: ["cherry", "apple", "banana"]
In this tutorial, we learned How to Shuffle an Array in Rust language with well detailed examples.