Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random sampling of a string slice

Tags:

rust

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
like image 277
Shane Avatar asked Oct 16 '25 21:10

Shane


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

like image 116
Solomon Ucko Avatar answered Oct 19 '25 13:10

Solomon Ucko