基本上,我想写一个返回闭包的函数.我怎么能不用返回Box<FnOnce(u32)>就完成这项任务呢?

closures chapter of the rust book中,我了解到闭包只是 struct 和impl FnOnce的语法糖.以下是我的try :

#[derive(Debug)]
struct MyError {
    code: u32,
    location: &'static str,
}
// Here is my closure:
struct MyErrorPartial {
    location: &'static str,
}
impl FnOnce(u32) for MyErrorPartial {
    type Output = MyError;

    fn call_once(self, args: u32) -> MyError {
        MyError {
            code: args,
            location: self.location,
        }
    }
}
fn error_at(location: &'static str) -> MyErrorPartial {
    MyErrorPartial {location: location}
}

fn function_returning_code() -> Result<(), u32> {
    Err(123)
}
fn function_with_error() -> Result<(), MyError> {
    try!(function_returning_code().map_err(error_at("line1")));
    try!(function_returning_code().map_err(error_at("line2")));
    Ok(())
}
fn main() {
    function_with_error().unwrap();
}

它目前给出了一个错误:

<anon>:11:12: 11:17 error: associated type bindings are not allowed here [E0229]
<anon>:11 impl FnOnce(u32) for MyErrorPartial {
                     ^~~~~

推荐答案

在 struct 上手动实现Fn* trait的语法如下:

impl FnOnce<(Arg1,Arg2,Arg3,)> for MyStruct {
    type Output = MyOutput;
    extern "rust-call" fn call_once(args: (Arg1, Arg2, Arg3,)) -> MyOutput {
       // implementation here
    }
}

请注意,所有参数都作为一个元组给出.

此外,这种语法不稳定,需要#![feature(core, unboxed_closures)],因此你不能在beta频道上使用,只能在夜间使用.

在你的情况下,它会这样翻译:

impl FnOnce<(u32,)> for MyErrorPartial {
    type Output = MyError;

    extern "rust-call" fn call_once(self, args: (u32,)) -> MyError {
        MyError {
            code: args.0,
            location: self.location,
        }
    }
}

Rust相关问答推荐

为什么迭代器上的`. map(...)`的返回类型如此复杂?

如何模拟/创建ReqData以测试Actix Web请求处理程序?

字段类型为Boxed的 struct 的生存期必须超过static

Rust&;Tokio:如何处理更多的信号,而不仅仅是SIGINT,即SIGQUE?

定义只有一些字段可以缺省的 struct

如果死 struct 实现了/派生了一些特征,为什么Rust会停止检测它们?

在macro_rule中拆分模块和函数名

为相同特征的特征对象使用 move 方法实现特征

当我编译 Rust 代码时,我是否缺少 AVX512 的目标功能?

随机函数不返回随机值

如何在 Rust 中编写一个通用方法,它可以接受任何可以转换为另一个值的值?

如何以与平台无关的方式将OsString转换为utf-8编码的字符串?

无法将`&Vec>`转换为`&[&str]`

如何将这些测试放在一个单独的文件中?

Rust/Serde/HTTP:序列化`Option`

为什么数组不像向量那样在 for 块之后移动?

意外的正则表达式模式匹配

从 Cranelift 发出 ASM

在 Rust 中返回对枚举变体的引用是个好主意吗?

A 有一个函数,它在 Option<> 类型中时无法编译,但在 Option<> 类型之外会自行编译.为什么?