FAQ - Help and questions

How do I translate C error codes and goto cleanup to Rust?

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

Short answer

Return a Result instead of an error code, and use the ? operator to return early on failure. The cleanup that C does under goto labels moves into Drop, so every early return releases what the function had acquired, without a label for each exit.

Checked with rustc 1.93.0, Windows 11

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

#1

Answer#

A C function that opens a file, allocates a buffer and reads into it usually returns 0 or -1, and uses goto fail labels so that each failure path frees exactly what had been acquired before it. In Rust the same function returns Result<T, E>. The ? operator returns the error from the function immediately, and values that own a resource (a File, a Vec, a Box) release it automatically when they go out of scope, on every path.

src/main.rsrust
use std::fs::File;
use std::io::{self, Read};

// C:   int load(const char *path, char **out) {
//          FILE *f = fopen(path, "rb"); if (!f) return -1;
//          char *buf = malloc(4096);    if (!buf) goto fail_file;
//          if (fread(buf, 1, 4096, f) == 0) goto fail_buf;
//          *out = buf; fclose(f); return 0;
//      fail_buf: free(buf);
//      fail_file: fclose(f); return -1; }
//
// Rust: errors are values, `?` returns early, and Drop does the cleanup on every path.
fn load(path: &str) -> io::Result<String> {
    let mut f = File::open(path)?; // closed automatically on every return path
    let mut text = String::new();
    f.read_to_string(&mut text)?;
    if text.is_empty() {
        return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "the file is empty"));
    }
    Ok(text)
}

fn main() {
    match load("definitely-missing.txt") {
        Ok(t) => println!("{} bytes", t.len()),
        Err(e) => println!("error kind {:?}: {e}", e.kind()),
    }
}

Output on Windows 11 with rustc 1.93.0 (the text after the colon comes from the operating system):

text
error kind NotFound: The system cannot find the file specified. (os error 2)

How to do it#

  1. Give the function a return type of Result<T, E>. Use std::io::Result<T> for I/O, or your own error enum when there are several kinds of failure.
  2. Replace each if (rc < 0) return rc; with ? after the call.
  3. Delete the goto labels and the free/fclose calls. Resources held in variables are released when the function returns.
  4. For something that has no Drop of its own (a handle from a C library), wrap it in a small struct and implement Drop for it.

Common mistakes#

  • Using unwrap() where C returned an error code. That turns a recoverable error into a panic.
  • Returning Option where the caller needs to know why it failed. Result carries the reason.
  • Keeping integer error codes as the error type. An enum with the cases is checked by match, and the compiler tells you when a case is not handled.

How do I return several kinds of error from one function?#

Define an enum with one variant per kind and implement std::fmt::Display and std::error::Error for it, or use Box<dyn std::error::Error> in application code where you only report the error.

What replaces errno?#

The error value itself. std::io::Error::last_os_error() reads the operating system's last error when you need it, but most functions already return it inside the Result.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet