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.
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):
error kind NotFound: The system cannot find the file specified. (os error 2)How to do it#
- Give the function a return type of
Result<T, E>. Usestd::io::Result<T>for I/O, or your own errorenumwhen there are several kinds of failure. - Replace each
if (rc < 0) return rc;with?after the call. - Delete the
gotolabels and thefree/fclosecalls. Resources held in variables are released when the function returns. - For something that has no
Dropof its own (a handle from a C library), wrap it in a small struct and implementDropfor it.
Common mistakes#
- Using
unwrap()where C returned an error code. That turns a recoverable error into a panic. - Returning
Optionwhere the caller needs to know why it failed.Resultcarries the reason. - Keeping integer error codes as the error type. An
enumwith the cases is checked bymatch, and the compiler tells you when a case is not handled.
Related questions#
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#
- The Rust Book, "Error Handling": https://doc.rust-lang.org/book/ch09-00-error-handling.html
- The Rust Book, "Running Code on Cleanup with the Drop Trait": https://doc.rust-lang.org/book/ch15-03-drop.html