【发布时间】:2020-10-11 10:16:13
【问题描述】:
我有这个代码:
use std::hash::Hash;
use std::rc::Rc;
struct Counter<V> {
value: V,
}
struct LFUCache<K, V> {
values: Vec<(Rc<K>, Counter<V>)>,
}
impl<K: Hash + Eq, V> IntoIterator for LFUCache<K, V> {
type Item = (Rc<K>, V);
type IntoIter = Box<dyn Iterator<Item=(Rc<K>, V)>>;
fn into_iter(self) -> Self::IntoIter {
return Box::new(self
.values
.into_iter()
.map(|(key, value_counter)| (key, value_counter.value)));
}
}
我收到一个错误:
error[E0310]: the parameter type `K` may not live long enough
--> src/lib.rs:167:16
|
162 | impl<K: Hash + Eq, V> IntoIterator for LFUCache<K, V> {
| -- help: consider adding an explicit lifetime bound `K: 'static`...
...
167 | return Box::new(self
| ________________^
168 | | .values
169 | | .into_iter()
170 | | .map(|(key, value_counter)| (key, value_counter.value)));
| |____________________________________________________________________^
|
note: ...so that the type `std::iter::Map<std::collections::hash_map::IntoIter<std::rc::Rc<K>, ValueCounter<V>>, [closure@src/lib.rs:170:18: 170:67]>` will meet its required lifetime bounds
--> src/lib.rs:167:16
|
167 | return Box::new(self
| ________________^
168 | | .values
169 | | .into_iter()
170 | | .map(|(key, value_counter)| (key, value_counter.value)));
我想表达盒装迭代器应该与 LFU 缓存一样长的意图。但是,由于没有引用,我无法获得任何生命周期。
我该如何解决这个问题?
【问题讨论】:
-
“由于没有引用,所以我无法获得任何生命周期” 不正确,您仍然可以引入新的生命周期参数并使用它们对其余部分应用生命周期约束的类型参数。它会像这样进行:
impl<'a, K: Hash + Eq + 'a, V: 'a> IntoIterator for LFUCache<K, V>,而不会忘记关联类型的相同界限(type IntoIter = Box<dyn Iterator<Item=(Rc<K + 'a>, V)> + 'a>等) -
这也有助于将来您在提问时创建一个正确的minimal reproducible example。这个缺少
LFUCache的定义。 -
@E_net4likesdownvotes 感谢您的指点。
Rc<K+'a>似乎无效,我收到一条错误消息,说它“不是特征” -
嗯,是的,应该只是
Rc<K>。我的错。 -
@nz_21 我强烈建议您阅读Common Rust Lifetime Misconceptions,因为您的困惑源于一些常见的误解,这些误解很难在一个单一的答案中简明扼要地解决。