You need to enable JavaScript to run this app. Rust如何编写接收闭包并返回对应闭包返回值的泛型函数?
优惠活动
大模型
产品
解决方案
定价
更多

Rust如何编写接收闭包并返回对应闭包返回值的泛型函数?

问题原因

你在定义函数约束时,T: Fn()的写法默认要求闭包返回单元类型(),和你传入的返回i32/&str的闭包类型不匹配,因此触发编译错误。

正确实现

通用版本(推荐)

使用FnOnce作为约束覆盖所有可用闭包场景,同时显式声明闭包返回类型泛型参数:

pub fn execute_code<F, R>(action: F) -> R
where
    F: FnOnce() -> R,
{
    println!("before:");
    let res = action();
    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);
}

保留传引用的版本

如果你的场景要求必须传入闭包的引用,可以调整约束如下:

pub fn execute_code<F, R>(action: &F) -> R
where
    F: Fn() -> R,
{
    println!("before:");
    let res = action();
    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);
}
说明

上述写法中我们新增了泛型参数R,通过Fn() -> R/FnOnce() -> R的约束,Rust会自动根据传入的闭包推导返回值类型,不需要硬编码指定返回类型,完全满足你的需求。

内容的提问来源于stack exchange,提问作者phip1611

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 16:15:03