Fondamentalmente, voglio scrivere una funzione che restituisce una chiusura. Come posso fare questo senza dover restituire Box<FnOnce(u32)>
?Come creare una chiusura di dimensioni o implementare Fn/FnMut/FnOnce su una struttura?
Da closures chapter of the rust book, ho letto che una chiusura è solo zucchero sintattico per una struttura e un impianto di FnOnce
. Qui è il mio tentativo:
#[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();
}
Attualmente dà un errore:
<anon>:11:12: 11:17 error: associated type bindings are not allowed here [E0229]
<anon>:11 impl FnOnce(u32) for MyErrorPartial {
^~~~~
E 'impossibile implementare 'Fn *' in stabile? – Kapichu
@Kapichu Appare così: i documenti per il collegamento del metodo ['call_once'] (https://doc.rust-lang.org/std/ops/trait.FnOnce.html#tymethod.call_once) al numero [# 29625 ] (https://github.com/rust-lang/rust/issues/29625), che è ancora aperto. –