yon*_*ran 7 higher-order-functions rust
基本上,我想编写一个返回闭包的函数.我怎么能这样做而不必返回Box<FnOnce(u32)>?
从Rust书的闭包章节,我读到一个闭包只是一个结构的语法糖和一个impl FnOnce.这是我的尝试:
#[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();
}
Run Code Online (Sandbox Code Playgroud)
它目前给出一个错误:
<anon>:11:12: 11:17 error: associated type bindings are not allowed here [E0229]
<anon>:11 impl FnOnce(u32) for MyErrorPartial {
^~~~~
Run Code Online (Sandbox Code Playgroud)
Fn*在结构上手动实现特征的语法是这样的:
impl FnOnce<(Arg1,Arg2,Arg3,)> for MyStruct {
type Output = MyOutput;
extern "rust-call" fn call_once(args: (Arg1, Arg2, Arg3,)) -> MyOutput {
// implementation here
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,所有参数都以单个元组的形式给出.
此外,此语法不稳定且需要#![feature(core, unboxed_closures)],因此您无法在测试版频道上使用它,只能在夜间播放.
在你的情况下,它会像这样翻译:
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,
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1335 次 |
| 最近记录: |