Random sampling of a string slice

Viewed 68

The objective is to take a set number of random samples from a string slice.

fn get_random_samples<'a>(kmers: &'a [&'a str], sample_size: usize) -> &'a [&'a str] {
    let mut rng = rand::thread_rng();

    kmers
        .choose_multiple(&mut rng, sample_size)
        .map(|item| *item)
        .collect::<Vec<&str>>()
        .as_slice()
}

But the above code gives the following compilation error which I have no idea how to fix.

error[E0515]: cannot return reference to temporary value
   --> src\lib.rs:382:5
    |
382 |        kmers
    |   _____^
    |  |_____|
    | ||
383 | ||         .choose_multiple(&mut rng, sample_size)
384 | ||         .map(|item| *item)
385 | ||         .collect::<Vec<&str>>()
    | ||_______________________________- temporary value created here
386 | |          .as_slice()
    | |____________________^ returns a reference to data owned by the current function
1 Answers

Just return the Vec directly (and remove the unnecessarily restrictive lifetime on the outer slice of kmers). Also, you can use Iterator::copied instead of map with deref.

fn get_random_samples<'a>(kmers: &[&'a str], sample_size: usize) -> Vec<&'a str> {
    let mut rng = rand::thread_rng();

    kmers
        .choose_multiple(&mut rng, sample_size)
        .copied()
        .collect::<Vec<&str>>()
}

Playground demo

Related