小编Ran*_*Man的帖子

从行迭代器构建哈希集

我不明白为什么这不起作用:

use std::collections::HashSet;

let test = "foo\nbar\n";

let hashset: HashSet<_> = test
    .lines()
    .collect::<Result<HashSet<_>, _>>()
    .unwrap()
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

类型的值Result<HashSet<_>, _>不能从一个迭代过类型的元素来构建&str

我试图使用中介,Vec但我也没有成功。我理解错误,但我不知道如何优雅地解决这个问题

这有效,但不是最快的解决方案:

use std::collections::HashSet;

let test = "foo\nbar\n";
let hashset = HashSet::new();

for word in test.lines() {
  hashset.insert(p.to_string());
}
Run Code Online (Sandbox Code Playgroud)

rust

1
推荐指数
1
解决办法
54
查看次数

如何修复此警告(无需收集)

我很难修复不必要的收集剪辑警告

pub fn import_selection(packages: &mut Vec<PackageRow>) -> io::Result<()> {
    let file = fs::File::open("uad_exported_selection.txt")?;
    let reader = BufReader::new(file);
    let imported_selection: Vec<String> = reader
        .lines()
        .map(|l| l.expect("Could not exported selection"))
        .collect();

    for (i,p) in packages.iter_mut().enumerate() {
        if imported_selection.contains(&p.name) {
            p.selected = true;
            ...
        } else {
            p.selected = false;
        }
    }
    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

我尝试直接从迭代器使用any(),它编译但似乎不起作用(它应该找到任何东西)

在这种情况下真的可以删除收集吗?

rust rust-clippy

0
推荐指数
1
解决办法
1408
查看次数

标签 统计

rust ×2

rust-clippy ×1