OneBite.Dev - Coding blog in a bite size

Shuffle The Elements In An Array In Rust

Code snippet for how to Shuffle The Elements In An Array In Rust with sample and detail explanation

Rust is a powerful programming language known for its excellent memory safety without sacrificing on the performance end. This article will walk you through a simple but concise way to shuffle the elements in an array using Rust, showcasing its array shuffling capabilities.

Code snippet for Shuffling Elements in an Array

Let’s begin by taking a look at a simple code snippet that illustrates how to shuffle the arrays.

use rand::seq::SliceRandom;
use rand::thread_rng;

fn main() {
    let mut arr = [1, 2, 3, 4, 5];
    let mut rng = thread_rng();
    arr.shuffle(&mut rng);
    println!("{:?}", arr);
}

Code Explanation for Shuffling Elements in an Array

Here’s a step by step breakdown of the code above to help you understand how it works in shuffling the elements in an array.

  1. use rand::seq::SliceRandom; use rand::thread_rng;: First, we import SliceRandom and thread_rng from the rand crate; SliceRandom provides the method to shuffle a slice, and thread_rng is a random number generator.

  2. fn main(): We define the main function, where our shuffling operation resides.

  3. let mut arr = [1, 2, 3, 4, 5];: We define a mutable array of integers we want to shuffle.

  4. let mut rng = thread_rng();: We create a mutable random number generator.

  5. arr.shuffle(&mut rng);: We call the shuffle method on our array, passing the mutable reference to our random number generator. This shuffle method is available thanks to SliceRandom trait. It shuffles the slice in place.

  6. println!("{:?}", arr);: Lastly, we print the shuffled array to the console.

Here, the mutation of the array is done in place, which means the initial array is shuffled, without making a copy of it. This makes the process of shuffling incredibly efficient, especially when dealing with big arrays.

By using this simple shuffle function in Rust, you can seamlessly shuffle the elements of any array, ensuring random and unpredictable output each time. This can be very useful when creating things like randomized quizzes, card games, and much more.

rust