在处理一些示例代码时,我发现我不能强迫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>。在不分配Strings的情况下,有什么方法可以绕过这个问题呢?
发布于 2020-03-16 02:18:57
没有必要使用不同类型的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]);(游乐场)
https://stackoverflow.com/questions/60698946
复制相似问题