Errors in Rust
In Rust, error handling is typically done using the Result
type, which represents either success (Ok
) or failure (Err
). This approach is similar to Go’s explicit error return, but with added type safety and pattern matching capabilities.
In this Rust code:
We define a custom
TeaError
type that implements theError
trait.Instead of using sentinel errors, we use static strings to represent specific error messages.
Functions that can fail return a
Result
type, which is eitherOk
with a value orErr
with an error.We use
Box<dyn Error>
to allow returning different error types from our functions.The
?
operator is used for early returns of errors, similar to how Go often checks for errors immediately.In
main
, we use pattern matching (match
) to handle theResult
types returned by our functions.To check for specific errors, we match on the error message string. This is less type-safe than Go’s
errors.Is
, but it’s a common pattern in Rust when dealing with error messages.
This Rust code demonstrates error handling patterns that are idiomatic to Rust while maintaining a similar structure to the original Go code.