How to create a size closure or implement Fn / FnMut / FnOnce in a structure?

Basically, I want to write a function that returns a closure. How can I do this without returning a Box<FnOnce(u32)> ?

From closes the head of rust , I read that closure is just syntactic sugar for the structure and impl FnOnce . Here is my attempt:

 #[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(); } 

An error message is currently being issued:

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

The syntax for the manual implementation of the Fn* attribute in the structure is:

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

Note that all arguments are specified as a single tuple.

In addition, this syntax is unstable and requires #![feature(core, unboxed_closures)] , so you cannot use it on the beta channel, only at night.

In your case, it will look like this:

 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, } } } 
+7
source

Source: https://habr.com/ru/post/984932/


All Articles