【发布时间】:2016-02-21 19:15:27
【问题描述】:
我试图在可迭代的序列中找到重复。此外,我想知道在那之前在该序列中发生的元素。
我创建了一个HashMap,并试图从take_while 使用的闭包中调用insert。但是,由于与具体/绑定生命周期相关的类型不匹配,到目前为止我还没有设法编译它。
这是我的代码的简化版本,显示相同的错误:
use std::collections::HashSet;
fn main() {
let mut seq = HashSet::new();
let mut insert = |k| seq.insert(k);
(1..10).cycle().take_while(insert);
}
这是我得到的错误:
error[E0631]: type mismatch in closure arguments
--> src/main.rs:6:21
|
5 | let mut insert = |k| seq.insert(k);
| ----------------- found signature of `fn(_) -> _`
6 | (1..10).cycle().take_while(insert);
| ^^^^^^^^^^ expected signature of `for<'r> fn(&'r {integer}) -> _`
error[E0271]: type mismatch resolving `for<'r> <[closure@src/main.rs:5:22: 5:39 seq:_] as std::ops::FnOnce<(&'r {integer},)>>::Output == bool`
--> src/main.rs:6:21
|
6 | (1..10).cycle().take_while(insert);
| ^^^^^^^^^^ expected bound lifetime parameter, found concrete lifetime
我需要如何更改代码才能使其工作?
【问题讨论】:
-
很好奇,如果将闭包直接移动到
take_while调用:is.gd/OgVK2i -
@ker,它之所以有效,是因为您正在做一件微妙不同的事情 - 您在模式中使用了隐式取消引用,而原始代码没有这样做。