Skip to content

Instantly share code, notes, and snippets.

@harryscholes
Last active July 24, 2021 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harryscholes/a7280f1eb2bb76e4c7a4dffaae936d68 to your computer and use it in GitHub Desktop.
Save harryscholes/a7280f1eb2bb76e4c7a4dffaae936d68 to your computer and use it in GitHub Desktop.
Rust automatic error conversion
use thiserror::Error;
#[derive(Debug, Error)]
enum A {
#[error("")]
ErrorA {},
}
#[derive(Debug, Error)]
enum B {
#[error("")]
ErrorB {},
}
// Try commenting this trait implementation out:
impl From<B> for A {
fn from(source: B) -> Self {
match source {
B::ErrorB {} => Self::ErrorA {},
}
}
}
fn f1() -> Result<(), A> {
Ok(f2()?)
}
fn f2() -> Result<(), B> {
Err(B::ErrorB {})
}
fn main() {
// `ErrorB` is automatically converted to `ErrorA`
println!("{:?}", f1());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment