Rust 当闭包包含复杂的生存期关系时,无法为函数生成等效闭包
编译器抱怨说,我在用等价闭包替换函数时遇到了一些麻烦Rust 当闭包包含复杂的生存期关系时,无法为函数生成等效闭包,rust,Rust,编译器抱怨说,我在用等价闭包替换函数时遇到了一些麻烦 cannot infer an appropriate lifetime due to conflicting requirements note: ...so that the types are compatible: expected &std::collections::BTreeSet<&str> found &std::collections::BTreeSet&
cannot infer an appropriate lifetime due to conflicting requirements
note: ...so that the types are compatible:
expected &std::collections::BTreeSet<&str>
found &std::collections::BTreeSet<&str> rustc(E0495)
除了放置
静态
生命周期之外,是否应该将具有此类错误的闭包转换为函数?这不是一件容易的事,但您可以使用返回类型定义外部闭包,它可以帮助您为内部闭包设置显式的生命周期边界。(通过对使用,这是一个级别更高的特征边界,您可以找到更多)
内部闭包需要Box
ed,因为编译时不知道Fn
trait的大小
let closure = |lower, upper| -> Box<for<'a> Fn(&BTreeSet<&'a str>) -> BTreeSet<&'a str>> {
Box::new(move |s: &BTreeSet<&str>| {
let mut r = BTreeSet::new();
r.extend(s.range(lower..=upper));
r
})
};
let closure=|下、上|->框)->BTreeSet@Shepmaster不确定是否存在重复,而且IMHO,使用for
的答案对于广泛的生命周期问题可能很有趣。