代码如下:
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/