Skip to main content

How to Return a Result from a Function in Rust

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

In Rust, a function that can fail says so in its return type, Result<T, E>. It returns Ok(value) when it works and Err(error) when it doesn't, and the code that calls it decides what to do with each.

Syntax​

Syntax
fn <name>(<parameters>) -> Result<T, E> {
if <failure> {
return Err(<error>);
}
Ok(<value>)
}
PartWhat it does
Result<T, E>The return type: T is the type of the value on success, E the type of the error.
return Err(<error>);Leaves the function at once with an error of type E.
Ok(<value>)The last expression, without a semicolon: the successful result, of type T.

The standard library's documentation for Result: "Result<T, E> is the type used for returning and propagating errors. It is an enum with the variants, Ok(T), representing success and containing a value, and Err(E), representing error and containing an error value."

The Example​

The example's divide function refuses to divide by zero: it returns an Err with a message instead of a number. The program calls it once with a valid divisor and once with zero.

Prerequisites​

  • Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.0.

Step 1: Create a Project​

Terminal
cargo new demo
cd demo
Output
Creating binary (application) `demo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

cargo new demo creates a folder named demo with a Cargo.toml file, which describes the project, and src/main.rs, which holds the code. cd demo moves into it.

Step 2: Write the Code​

Replace the contents of src/main.rs with:

src/main.rs, where divide returns Result of i32 and String, giving Err with cannot divide by zero when b is 0 and Ok of a divided by b otherwise, and main prints divide(10, 2) and divide(1, 0).

src/main.rs
fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
return Err(String::from("cannot divide by zero"));
}
Ok(a / b)
}

fn main() {
println!("{:?}", divide(10, 2));
println!("{:?}", divide(1, 0));
}

Result<i32, String> says the function gives back an i32 on success or a String describing the error. {:?} prints the whole Result, so you can see which variant came back.

Step 3: Run It​

Terminal
cargo run -q
Output
Ok(5)
Err("cannot divide by zero")

A zsh terminal where cargo run -q prints Ok(5) and then Err("cannot divide by zero").

cargo run compiles the program and runs it, and -q hides Cargo's own status lines. Ten divided by two came back as Ok(5), and the division by zero as Err with the message.

Handle Both Cases with match​

A caller usually takes the Result apart with match, which runs one arm for Ok and another for Err. Replace main with:

src/main.rs
fn main() {
match divide(1, 0) {
Ok(n) => println!("{n}"),
Err(e) => println!("Error: {e}"),
}
}
Output
Error: cannot divide by zero

Ok(n) and Err(e) give the value inside each variant a name for that arm.

Common Mistakes​

MistakeWhat happensDo this instead
Calling the function and ignoring what it returns, as in divide(1, 0);warning: unused `Result` that must be used: the error goes unnoticedHandle it with match, if let or ?
Returning the plain value, a / b, at the enderror[E0308]: mismatched types, with expected `Result<i32, String>`, found `i32` Wrap it: Ok(a / b), as the compiler's help line suggests
A semicolon after Ok(a / b)error[E0308]: mismatched types, expected `Result<i32, String>`, found `()` , with the help remove this semicolon to return this valueLeave the last expression without a semicolon

Troubleshooting​

SymptomLikely causeFix
expected `Result<…>`, found `…` A path returns the plain valueWrap it in Ok(…)
unused `Result` that must be usedThe caller drops the ResultHandle both cases

FAQ​

What type should the error be?​

A String is the simplest, as in the example. Standard library functions return their own error types: "forty".parse::<i32>() returns a ParseIntError, for example.

Why not stop the program on an error?​

Because the caller may know what to do: show a message, try again or use a default. The Rust Book calls these recoverable errors and uses Result for them.

Conclusion​

Give a function that can fail the return type Result<T, E>, return Err(…) on failure and Ok(…) on success, and let the caller handle both with match.

Additional Resources​