Search code examples
sortingrandomrustsample

Rust error when using sort with seq::index::sample


So I was trying to generate a sample of 5 numbers with:

use rand::{thread_rng, seq};
use std::time::SystemTime;

fn main(){
    let mut rng = thread_rng();

    let mut sample = seq::index::sample(&mut rng, 50, 5);
}

But when I try to sort it with:

sample.sort();

It gives me the following error:

error[E0599]: no method named sort found for type rand::seq::index::IndexVec in the current scope --> src/main.rs:12:16

How can I sort a random sample of numbers?


Solution

  • rand::seq::index::sample returns an rand::seq::index::IndexVec rather than a regular Vec. This type seems to be mostly intended to be iterated and does not have many methods. In particular, it has no sort method.

    You can use into_vec to get a normal Vec, which is sortable.