gpt4 book ai didi

rust - 实现返回HashMap::IntoIter的IntoIterator时的“wrong number of type arguments”

转载 作者:行者123 更新时间:2023-12-03 11:34:13 24 4
gpt4 key购买 nike

我有以下代码:

use std::{collections::HashMap, hash::Hash, rc::Rc};

#[derive(Debug)]
pub struct LFUCache<K: Hash + Eq, V> {
values: HashMap<Rc<K>, ValueCounter<V>>,
capacity: usize,
min_frequency: usize,
}

#[derive(Debug)]
struct ValueCounter<V> {
value: V,
count: usize,
}

impl<K: Hash + Eq, V> IntoIterator for LFUCache<K, V> {
type Item = (Rc<K>, V);
type IntoIter = std::collections::HashMap::IntoIter<Rc<K>, V>;

fn into_iter(self) -> Self::IntoIter {
return self
.values
.into_iter()
.map(|(key, valueCounter)| (key, valueCounter.value));
}
}


它抛出一个错误,说:

error[E0107]: wrong number of type arguments: expected at least 2, found 0
--> src/lib.rs:18:21
|
18 | type IntoIter = std::collections::HashMap::IntoIter<Rc<K>, V>;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected at least 2 type arguments

我查看了文档,发现我的用例非常类似于 to the example

我该如何解决?

最佳答案

HashMap::IntoIter IntoIterator 特性的关联类型,没有任何类型参数。 HashMap可以:HashMap::<Rc<K>, V>::IntoIter。那是模棱两可的,因此您必须完全限定它:

type IntoIter = <std::collections::HashMap::<Rc<K>, V> as IntoIterator>::IntoIter;

通常表示为
type IntoIter = std::collections::hash_map::IntoIter<Rc<K>, V>;

然后,您遇到的问题是您试图对编译器撒谎,因为您没有返回该类型:

error[E0308]: mismatched types
--> src/lib.rs:21:9
|
21 | / self.values
22 | | .into_iter()
23 | | .map(|(key, valueCounter)| (key, valueCounter.value))
| |_________________________________________________________________^ expected struct `std::collections::hash_map::IntoIter`, found struct `std::iter::Map`
|
= note: expected struct `std::collections::hash_map::IntoIter<_, V>`
found struct `std::iter::Map<std::collections::hash_map::IntoIter<_, ValueCounter<V>>, [closure@src/lib.rs:23:18: 23:65]>`

按照链接的问题提示,您最终得到
use std::{collections::hash_map::IntoIter, iter::Map};

impl<K: Hash + Eq, V> IntoIterator for LFUCache<K, V> {
type Item = (Rc<K>, V);
type IntoIter =
Map<IntoIter<Rc<K>, ValueCounter<V>>, fn((Rc<K>, ValueCounter<V>)) -> (Rc<K>, V)>;

fn into_iter(self) -> Self::IntoIter {
fn xform<K, V>((key, vc): (Rc<K>, ValueCounter<V>)) -> (Rc<K>, V) {
(key, vc.value)
}

self.values.into_iter().map(xform)
}
}

也可以看看:
  • How do I return a Filter iterator from a function?
  • What is the correct way to return an Iterator (or any other trait)?
  • 关于rust - 实现返回HashMap::IntoIter的IntoIterator时的“wrong number of type arguments”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61639695/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com