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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With