Skip to main content

SliceExt

Trait SliceExt 

Source
pub trait SliceExt {
    type Item;

    // Required methods
    fn choose(&self) -> Option<&Self::Item>;
    fn choose_mut(&mut self) -> Option<&mut Self::Item>;
    fn shuffle(&mut self);
}
Expand description

A trait providing extension methods for slices.

This trait adds several useful methods for working with slices. It provides:

  • choose: Randomly selects an element from the slice.
  • choose_mut: Randomly selects and mutably borrows an element from the slice.
  • shuffle: Shuffles the slice in place.

These methods operate on slices of any type T and assume that T is a type that can be accessed and modified within the slice.

§Examples

use regd_testing::prelude::*;

let mut numbers = [1, 2, 3, 4, 5];
numbers.shuffle();
println!("Shuffled numbers: {:?}", numbers);

if let Some(choice) = numbers.choose() {
    println!("Random choice: {}", choice);
}

if let Some(choice) = numbers.choose_mut() {
    *choice = 10;
    println!("Modified choice: {}", choice);
}

Required Associated Types§

Source

type Item

The type of elements in the slice.

Required Methods§

Source

fn choose(&self) -> Option<&Self::Item>

Randomly selects an element from the slice.

§Returns
  • Some(&Self::Item) if the slice is non-empty.
  • None if the slice is empty.
Source

fn choose_mut(&mut self) -> Option<&mut Self::Item>

Randomly selects and mutably borrows an element from the slice.

§Returns
  • Some(&mut Self::Item) if the slice is non-empty.
  • None if the slice is empty.
Source

fn shuffle(&mut self)

Shuffles the elements of the slice in place.

This method shuffles the slice, reordering its elements randomly.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<T> SliceExt for [T]

Source§

type Item = T

Source§

fn choose(&self) -> Option<&Self::Item>

Source§

fn choose_mut(&mut self) -> Option<&mut Self::Item>

Source§

fn shuffle(&mut self)

Implementors§