簡體   English   中英

無法將 HashSet<&str> 強制轉換為 HashSet<&String>

[英]Cannot coerce HashSet<&str> into HashSet<&String>

在處理一些示例代碼時,我發現我無法將HastSet<&String>強制HastSet<&String>HashSet<&str> ,反之亦然。

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

游樂場

編譯器錯誤

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> 有什么方法可以在不分配String的情況下解決這個問題?

不需要有不同類型的HashSet found更改為HashSet<&str>並且程序可以運行。

// 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]);

游樂場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM