FAQ - Help and questions

How do Go error returns, errors.Is and defer map to Rust?

#porting#golang#error-handlingpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A Go function returning a value and an error becomes a Result, if err != nil return becomes the question mark operator, and wrapping with percent w becomes a From conversion that keeps the cause as the source. errors.Is and errors.As become match and downcast_ref, and defer becomes Drop.

Checked with rustc 1.93.0, Go 1.26.5, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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 }.

GoRust
func f() (int, error)fn f() -> Result<i32, MyError>
if err != nil { return 0, err }? after the call
errors.New("x"), sentinel var ErrXan 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 / recoverpanic! for bugs; do not use as control flow

Go (1.26.5):

go
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)
	}
}
text
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 file

Rust (1.93.0):

src/main.rsrust
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);
    }
}
text
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 file

The 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#

  1. Make one error enum per package (module). Sentinel errors become variants; wrapped errors become variants holding the cause.
  2. Change each (T, error) return to Result<T, YourError>.
  3. Replace if err != nil { return ..., err } by ?, adding From implementations for the causes you want converted automatically.
  4. Replace defer by owning values with Drop, or by code after the match when it is only a statement. Several defer calls run last-in first-out; Rust drops locals in reverse order of declaration, too.
  5. Replace errors.As by a match on your own enum where possible. Walk the source() 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 unused Result; handle it or let _ = it on purpose.
  • Putting defer-like cleanup in a closure called at the end of the function. It will be skipped by an early ?; use Drop.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet