Reference 引用上的标识闭包

Reference 引用上的标识闭包,reference,rust,closures,lifetime,Reference,Rust,Closures,Lifetime,我有一个接受闭包的函数。闭包接受引用并返回任何类型K: fn take_closure<T, K>(f: impl FnMut(&T)->K) {/*...*/} 编译器抱怨: error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements 我认为问题在于K是一种单一类型,但闭包必须在所有生命周期内都有效,因此闭包的结果必须类似于K+'(闭包参数的生命周期) 指定K

我有一个接受闭包的函数。闭包接受引用并返回任何类型
K

fn take_closure<T, K>(f: impl FnMut(&T)->K) {/*...*/}
编译器抱怨:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
我认为问题在于
K
是一种单一类型,但闭包必须在所有生命周期内都有效,因此闭包的结果必须类似于
K+'(闭包参数的生命周期)

指定
K
的寿命与
&T
的寿命一样长并没有真正的帮助:

fn take_closure<'a, T: 'a + Default, K: 'a>(mut f: impl FnMut(&'a T)->K) {
    let t = Default::default();
    f(&t); // error[E0597]: `t` does not live long enough
}
fn拿着_closureK){
设t=Default::Default();
f(&t);//错误[E0597]:`t`寿命不够长
}
因此,我尝试了更高的等级特征界限:

fn take_closure<F, T: Default, K>(mut f: F)
    where for<'a> F: FnMut(&'a T)->K // <- (how) can I specify that K: 'a 
{
    let t = Default::default();
    f(&t);
}

#[derive(Default)]
struct S;
fn test() {
    take_closure(|s: &S| s) // error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
}
fn take_闭包(mut f:f)

其中forK/
,my
FnMut(&'at)
产生一个
K
满足生存期
'a

您可以在声明函数时指定
K
不能超过
&T

fn take_closureK){
结构;
fn测试(){
采取封闭措施(s:&s)
}

您打算如何准确地通过返回
S
(借用)将
&S
(借用)转换为
K
(拥有)呢?那里有一些非常可疑的事情。@sébastienRenauld我认为
K
不一定是自己的。特别是,我们选择了
K==&S
(至少我是这么认为的)。对不起,我把我的问题简化得太多了。实际上,我试过这个,但是如果我真的想在
take\u closure
中使用
f
,这个方法就行不通了。我想至少我必须为
FnMut
指定任意的生存期(参见我编辑的问题)。谢谢你的回答。
fn take_closure<F, T: Default, K>(mut f: F)
    where for<'a> F: FnMut(&'a T)->K // <- (how) can I specify that K: 'a 
{
    let t = Default::default();
    f(&t);
}

#[derive(Default)]
struct S;
fn test() {
    take_closure(|s: &S| s) // error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
}