closures - 如何使用一个闭包作为另一个闭包的参数?

标签 closures rust type-inference

代码如下:

fn main() {
  let arg = | | println!("closure");
  let call_twice = | c | { c(); c(); };
  call_twice(arg);
}

但编译器无法推断出参数的正确类型 c .错误信息:

error: the type of this value must be known in this context

我怎样才能告诉编译器参数的类型是泛型类型,这意味着 Fn


编辑:如果参数类型是特征对象,编译器可以接受代码。但是间接性不是必需的,对吗?

fn main() {
  let arg = | | println!("closure");
  let call_twice = | c :&Fn() | { c(); c(); };
  call_twice(&arg);
}

感谢您的回答。但让我困惑的是类型推断问题。使用 fn可以让编译器开心。

fn main() {
 let arg = | | println!("closure");

 // now compiler knows the argument `c` is a closure
 fn call_twice<F>(c: F) where F:Fn() {c(); c();}

 call_twice(arg);
}

我们可以添加一个语法来支持类似的功能吗?如for<F> | c:F | where F:Fn() {c(); c();} .

最佳答案

正在关注 the guidelines in the Rust book section on returning closures将闭包变成 move 闭包并将其装箱,这就是我必须做的才能让你的程序在 the Rust Playground 处运行:

fn main() {
    let arg = Box::new(move || println!("closure"));
    let call_twice = |c: Box<Fn()>| { c(); c(); };
    call_twice(arg);
}

编辑以解决 OP 的最新编辑:不。您正在处理的问题最终不是类型推断问题。如果它只是类型推断,那么我们所要做的就是告诉闭包 c 是一个闭包。实际问题是“闭包参数必须是局部变量,并且所有局部变量的大小必须在编译时已知。”另一方面,Rust 函数参数显然没有这个要求。

关于closures - 如何使用一个闭包作为另一个闭包的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34703611/

相关文章:

javascript - 使用闭包 : Not working? 循环(使用 jqueryui)

rust - 为什么对不明确的数字进行方法调用会导致错误?

c# - 选择集合的返回类型 : Is there a way to return the same type that is provided?

python - Python 的闭包是如何工作的

javascript - 如何在 jQuery 之前加载的闭包中检查/使用 jQuery?

rust - 更高等级的生命周期和泛型表现不佳

rust - 如何从特征对象中获取对具体类型的引用?

rust - 我可以拥有既可以从切片又可以从拥有的缓冲区构造的结构吗?

rust - 使用带有 Rc 的闭包时,无法在 Fn 闭包中借用捕获的外部变量

Java - 类型删除和类型推断有什么区别?