|
|
|
|
|
by TheDong
1544 days ago
|
|
It was not a joke. Let's look at a common example: you want to return two different types of errors and have the caller distinguish between them. Let me show it to you in rust and go. Rust: #[derive(Error, Debug)]
pub enum MyErrors {
#[error("NotFound: {0}")
NotFound(String),
#[error("Internal error")]
Internal(#[source] anyhow::Error),
}
The equivalent go would be something like: type NotFoundErr struct {
msg string
}
func (err NotFoundErr) Error() string {
return "NotFound: " + err.msg
}
func (err NotFoundErr) Is(target error) bool {
if target == nil {
return false
}
// All NotFoundErrs are considered the same, regardless of msg
_, ok := target.(NotFoundErr)
return ok
}
type InternalErr struct {
wrapped error
}
func (err InternalErr) Error() string {
return fmt.Sprintf("Internal error: %s", err.wrapped)
}
func (err InternalErr) Unwrap() error {
return err.wrapped
}
|
|
https://github.com/dtolnay/thiserror/blob/master/src/lib.rs