首页 > 解决方案 > 如何将 HashSet<&String> 转换为 HashSet?

问题描述

当我执行这部分代码时,出现错误。我知道我必须转换价值,但如何?

编码:

let cleaned_vec:HashSet<_> = new_file_vec.difference(&new_file_vec2).collect();
new_file_vec=cleaned_vec.clone();

错误:

   |         new_file_vec=cleaned_vec.clone();
   |                      ^^^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found `&std::string::String`
   |
   = note: expected struct `std::collections::HashSet<std::string::String>`
              found struct `std::collections::HashSet<&std::string::String>`

标签: rust

解决方案


clone只是克隆里面的引用。你实际上是在转换数据,所以你应该得到一个迭代器,映射克隆,然后收集回一个HashSet

let owned_set: HashSet<String> = borrowed_set.iter().map(|&x| x.clone()).collect();

游乐场链接


推荐阅读