rust - 字符串切片的随机采样

标签 rust

目标是从字符串切片中获取一定数量的随机样本。

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()
}

但是上面的代码给出了以下编译错误,我不知道如何修复。

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

最佳答案

只需直接返回 Vec(并移除 kmers 外部切片上不必要的限制性生命周期)。此外,您可以使用 Iterator::copied用 deref 代替 map

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

关于rust - 字符串切片的随机采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70934594/

相关文章:

closures - 如何在 Rust 中捕获闭包范围之外的变量?

rust - 路径语句在移动状态中留下一个值?

rust - 如何永久关闭瓶盖

cuda - 使用 cc 更改 Rust 传递给 nvcc 的编译参数

rust - 如何在 .unzip() 返回的每个迭代器上使用 .collect()?

rust - 在 Vector 中查找 dyn 特征的索引

ssl - 为什么 reqwest 需要安装 OpenSSL?

rust - 如何为Chrono NaiveDate添加一个月?

function - 向预先存在的结构添加功能

rust - 如何在 Rust 中构建向量的 HashMap?