基本上,我想编写一个返回闭包的函数。如何做到这一点而不必返回 Box<FnOnce(u32)>
?
从 Rust 书籍的闭包章节中,我了解到闭包只是结构体和 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();
}
目前它会给出一个错误:
<anon>:11:12: 11:17 error: associated type bindings are not allowed here [E0229]
<anon>:11 impl FnOnce(u32) for MyErrorPartial {
^~~~~
Fn*
? - Kapichucall_once
方法的文档链接到问题#29625,该问题仍然未解决。 - Sam Estep