我正在尝试编写一个函数,它接受一个闭包并返回任何闭包返回类型。我不想要硬编码的返回类型,比如 fn(action: &dyn Fn()) -> i32
。我试图解决它,如下所示:
pub fn execute_code<T>(actions: T) -> T::Output
where
T: Fn(),
{
println!("before:");
let res = actions();
println!("after:");
res
}
fn main() {
let i32_res: i32 = execute_code(&|| 5 + 5);
let str_res: &str = execute_code(&|| "a string");
println!("i32_res: {}, string_res: {}", i32_res, str_res);
}
但是编译器(1.53 稳定版)抱怨:
pub fn execute_code<T>(actions: T) -> T::Output
| ------------ required by a bound in this
2 | where
3 | T: Fn(),
| ---- required by this bound in `execute_code`
...
12 | let i32_res: i32 = execute_code(&|| 5 + 5);
| ^^^^^^^^^^^^ expected `()`, found integer
实现这一目标的正确方法是什么?
答案 0 :(得分:2)
您只需要将输出参数化为另一种类型:
pub fn execute_code<T, R>(actions: T) -> R
where
T: Fn() -> R,
{
println!("before:");
let res = actions();
println!("after:");
res
}
fn main() {
let i32_res: i32 = execute_code(&|| 5 + 5);
let str_res: &str = execute_code(&|| "a string");
println!("i32_res: {}, string_res: {}", i32_res, str_res);
}