Answer#
Go and Rust agree on a basic point: errors are ordinary values, returned and checked, not exceptions thrown. The port is therefore close. The differences are that Rust's Result makes the two outcomes one value that cannot be used without checking, and that ? replaces the repeated if err != nil { return ..., err }.
| Go | Rust |
|---|---|
func f() (int, error) | fn f() -> Result<i32, MyError> |
if err != nil { return 0, err } | ? after the call |
errors.New("x"), sentinel var ErrX | an enum variant (MyError::X) |
fmt.Errorf("port: %w", err) | a variant holding the cause, and From<CauseError> for MyError |
errors.Is(err, ErrMissing) | matches!(err, MyError::Missing) or a match arm |
errors.As(err, &target) | walk source() and downcast_ref::<T>() |
defer f.Close() | Drop on a value that owns the resource |
panic / recover | panic! for bugs; do not use as control flow |
Go (1.26.5):
var ErrMissing = errors.New("port: missing")
func getPort(raw *string) (int, error) {
if raw == nil {
return 0, ErrMissing
}
n, err := strconv.Atoi(*raw)
if err != nil {
return 0, fmt.Errorf("port: %w", err)
}
return n, nil
}
func run(raw *string) {
defer fmt.Println(" deferred: close the file")
p, err := getPort(raw)
var numErr *strconv.NumError
switch {
case err == nil:
fmt.Println(" port", p)
case errors.Is(err, ErrMissing):
fmt.Println(" using the default port")
case errors.As(err, &numErr):
fmt.Println(" chain contains a NumError:", numErr)
fmt.Println(" error:", err)
}
}input 8080
port 8080
deferred: close the file
input nil
using the default port
deferred: close the file
input http
chain contains a NumError: strconv.Atoi: parsing "http": invalid syntax
error: port: strconv.Atoi: parsing "http": invalid syntax
deferred: close the fileRust (1.93.0):
use std::error::Error;
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum PortError {
Missing,
Invalid(ParseIntError),
}
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
PortError::Missing => write!(f, "port: missing"),
PortError::Invalid(e) => write!(f, "port: {e}"),
}
}
}
impl Error for PortError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
PortError::Invalid(e) => Some(e),
PortError::Missing => None,
}
}
}
// `?` calls this conversion, the counterpart of wrapping with %w
impl From<ParseIntError> for PortError {
fn from(e: ParseIntError) -> Self {
PortError::Invalid(e)
}
}
fn get_port(raw: Option<&str>) -> Result<u16, PortError> {
let raw = raw.ok_or(PortError::Missing)?;
Ok(raw.parse::<u16>()?)
}
// Go: defer f.Close() runs when the function returns, in reverse order
struct Deferred(&'static str);
impl Drop for Deferred {
fn drop(&mut self) {
println!(" deferred: {}", self.0);
}
}
fn run(raw: Option<&str>) {
let _close = Deferred("close the file");
match get_port(raw) {
Ok(p) => println!(" port {p}"),
// errors.Is(err, ErrMissing)
Err(PortError::Missing) => println!(" using the default port"),
// errors.As: look through the chain of causes for a ParseIntError
Err(e) => {
let mut cause: Option<&dyn Error> = Some(&e);
while let Some(c) = cause {
if let Some(p) = c.downcast_ref::<ParseIntError>() {
println!(" chain contains a ParseIntError: {p}");
}
cause = c.source();
}
println!(" error: {e}");
}
}
}
fn main() {
for raw in [Some("8080"), None, Some("http")] {
println!("input {raw:?}");
run(raw);
}
}input Some("8080")
port 8080
deferred: close the file
input None
using the default port
deferred: close the file
input Some("http")
chain contains a ParseIntError: invalid digit found in string
error: port: invalid digit found in string
deferred: close the fileThe sequence matches. The message texts differ because they come from each language's number parser, so port them if anything compares text. Where the Go code compares by identity (errors.Is), the Rust code compares by variant, which the compiler checks for completeness.
How to do it#
- Make one error enum per package (module). Sentinel errors become variants; wrapped errors become variants holding the cause.
- Change each
(T, error)return toResult<T, YourError>. - Replace
if err != nil { return ..., err }by?, addingFromimplementations for the causes you want converted automatically. - Replace
deferby owning values withDrop, or by code after thematchwhen it is only a statement. Severaldefercalls run last-in first-out; Rust drops locals in reverse order of declaration, too. - Replace
errors.Asby amatchon your own enum where possible. Walk thesource()chain only for errors that come from other crates.
Common mistakes#
- Defining the error as a
String. Callers can no longer match on the kind. - Ignoring an error value in Go style (
_ = f()). Rust warns about an unusedResult; handle it orlet _ =it on purpose. - Putting
defer-like cleanup in a closure called at the end of the function. It will be skipped by an early?; useDrop.
Related questions#
Is there a crate that removes the boilerplate?#
Crates such as thiserror and anyhow are common. This thread used only the standard library; the crates were not run.
What replaces Go's panic and recover?#
panic! and std::panic::catch_unwind, which exist for boundaries such as FFI and thread pools. Normal error handling should use Result.
Sources#
- The Rust Book, "Recoverable Errors with Result": https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
- Go blog, "Working with Errors in Go 1.13": https://go.dev/blog/go1.13-errors