【问题标题】:How to convert HashSet<&String> to HashSet<String>?如何将 HashSet<&String> 转换为 HashSet<String>?
【发布时间】:2021-03-13 17:37:58
【问题描述】:

当我执行这部分代码时,我得到一个错误。我知道我必须转换值,但是如何转换?

代码:

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


    【解决方案1】:

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

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

    Playground link

    【讨论】:

      猜你喜欢
      • 2011-07-25
      • 2021-07-14
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2018-05-07
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多