Sub topic 3
Result<T, E>: an operation that may fail
This chapter assumes you know basic Rust syntax, enums and match, and have a conceptual grasp of generics. You should also have read the previous chapter on Option<T>.
What Result is
Option<T> says a value may be missing. It doesn't say why. When an operation can fail for a reason the caller may want to know, Rust uses Result<T, E>. The standard library defines it as an enum with two variants:
enum Result<T, E> {
Ok(T),
Err(E),
}Ok(T) holds the success value. Err(E) holds an error value. T and E are independent type parameters, so each function chooses its own success and error types. Ok, Err, and Result are in the prelude, so you don't import them.
A first example
The standard library's parse method returns a Result. Parsing a string into u16 can fail, so the return type says so:
use std::num::ParseIntError;
fn parse_port(s: &str) -> Result<u16, ParseIntError> {
s.trim().parse::<u16>()
}
fn main() {
println!("{:?}", parse_port("8080"));
println!("{:?}", parse_port("abc"));
}This prints:
Ok(8080)
Err(ParseIntError { kind: InvalidDigit })A bad input does not throw an exception. It becomes an ordinary Err value that flows through the program like any other value.
Why the type matters
The success value is wrapped inside Ok. You can't use a Result<u16, _> as if it were a u16. The compiler makes you unwrap it, and that forces you to decide what happens on the error path.
flowchart TDThe diagram below shows the two outcomes of a fallible call.
Choosing the error type
The error type E can be any type. A String is the simplest, and it is fine for small programs:
fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
Err(String::from("division by zero"))
} else {
Ok(a / b)
}
}
fn main() {
match divide(10, 2) {
Ok(q) => println!("quotient {q}"),
Err(msg) => println!("error: {msg}"),
}
match divide(1, 0) {
Ok(q) => println!("quotient {q}"),
Err(msg) => println!("error: {msg}"),
}
}Strings are hard to inspect in code, because callers can only compare text. Later chapters replace them with custom error enums.
Common mistakes
- Ignoring the result.
Resultis marked#[must_use]. If you call a fallible function and drop the value, the compiler warns you. Don't silence the warning. Handle theErr. - Treating
Okas the only case. Writing code that assumes success moves the failure to runtime. Usematchor the other tools covered in the next chapters. - Mismatched error types. A function returning
Result<u16, String>can't return anErr(ParseIntError)directly. The types must match or be converted.
Exercise
Write the signature of a function read_age that takes a &str and returns the age as a u8, or the parse error if the text is not a valid u8. What does read_age("300") return?
Show answer
The signature is fn read_age(s: &str) -> Result<u8, std::num::ParseIntError>. The value 300 does not fit in a u8, so read_age("300") returns an Err holding a ParseIntError (its kind is PosOverflow).