【发布时间】:2020-07-17 07:45:07
【问题描述】:
我正在尝试解决一个涉及比较两组的在线挑战。我按照this 的回答将我的Vec<i32> 输出转换为HashSet
use std::collections::HashSet;
use std::iter::FromIterator;
struct Solution {}
impl Solution {
pub fn solve(nums: Vec<i32>, k: i32) -> Vec<i32> {
// todo, return dummy for now
return vec![1, 2];
}
}
fn main() {
assert_eq!(
HashSet::from_iter(Solution::solve(vec![1, 2, 3], 2)),
HashSet::from_iter(vec![1i32, 2i32])
)
}
由于我还不明白的原因,编译失败:
error[E0282]: type annotations needed
--> src/main.rs:15:9
|
15 | HashSet::from_iter(Solution::solve(vec![1, 2, 3], 2)),
| ^^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `S` declared on the struct `HashSet`
它适用于HashSet::from_iter(vec![1i32, 2i32])
我尝试添加像HashSet::from_iter::<Vec<i32>> 这样的类型注释,但无济于事。我也阅读了source implementation,但仍然无法弄清楚编译器抱怨的原因。
我可以通过显式声明或使用 for 循环和 inserts 构造 HashSet 来解决它,但我想了解这里发生了什么。
我正在使用 Rust 1.43.1。
【问题讨论】:
-
仅供参考,Rust Github repo 上针对此行为提出了一个问题:HashMap::from_iter doesn't compile without explicitly supplying the hasher
标签: rust