Skip to content

Instantly share code, notes, and snippets.

@Denommus
Created October 1, 2018 21:14
Show Gist options
  • Save Denommus/a18cbdecf30c2d942c90ca4cf65644ee to your computer and use it in GitHub Desktop.
Save Denommus/a18cbdecf30c2d942c90ca4cf65644ee to your computer and use it in GitHub Desktop.
trait PrintError<E> {
fn print_err(self, message: &'static str) -> Self;
// The String type is allocated in the heap, so when a String is needed it's better to have a function that only allocates it in case it's necessary
fn print_err_with<F>(self, message_f: F) -> Self
where F: Fn(&E) -> String;
}
impl<T, E> PrintError<E> for Result<T, E> {
fn print_err(self, message: &'static str) -> Result<T, E> {
self.map_err(|err| {
println!("{}", message);
err
})
}
fn print_err_with<F>(self, message_f: F) -> Result<T, E>
where F: Fn(&E) -> String {
self.map_err(|err| {
println!("{}", message_f(&err));
err
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment