首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不能强迫HashSet<&str>进入HashSet<&String>

不能强迫HashSet<&str>进入HashSet<&String>
EN

Stack Overflow用户
提问于 2020-03-16 00:12:02
回答 1查看 93关注 0票数 0

在处理一些示例代码时,我发现我不能强迫HastSet<&String>进入HashSet<&str>,反之亦然。

代码语言:javascript
复制
use std::collections::HashSet;

fn main() {
    // move strings into HashSet
    let known_values: HashSet<&str> = ["a", "b", "c"]
        .iter().cloned().collect();

    // provided an Vec<String>
    let provided_values: Vec<String> = vec![
        "a".to_string(),
        "b".to_string(),
        "z".to_string()
    ];

    // hash set of refrences
    let mut found: HashSet<&String> = HashSet::new();
    found.insert(&provided_values[0]);
    found.insert(&provided_values[1]);
    found.insert(&provided_values[2]);

    //let missing = known_values.difference(&found);
    let missing = found.difference(&known_values);

    println!("missing: {:#?}", missing);
}

(游乐场)

编译器错误

代码语言:javascript
复制
error[E0308]: mismatched types
  --> src/main.rs:23:36
   |
23 |     let missing = found.difference(&known_values);
   |                                    ^^^^^^^^^^^^^ expected struct `std::string::String`, found `str`
   |
   = note: expected reference `&std::collections::HashSet<&std::string::String>`
              found reference `&std::collections::HashSet<&str>`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.

我知道你可以强迫&String进入&str,反之亦然,所以我有点惊讶它没有扩展到HashSet<&String>HashSet<&str>。在不分配Strings的情况下,有什么方法可以绕过这个问题呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-16 02:18:57

没有必要使用不同类型的HashSet。将found更改为HashSet<&str>,程序就可以工作了。

代码语言:javascript
复制
// hash set of references
let mut found: HashSet<&str> = HashSet::new();
found.insert(&provided_values[0]);
found.insert(&provided_values[1]);
found.insert(&provided_values[2]);

(游乐场)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60698946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档