Result<T, E>
- Rust course
- Beginner
- Lesson 106/115
- 4 min
Learn the Result<T, E> type and its Ok/Err variants.
Result<T, E>
Rust splits errors into two groups: recoverable errors (file missing, invalid input) are returned with Result; unrecoverable errors (bugs) stop the program with panic!. Result is an enum:
enum Result<T, E> {
Ok(T), // success and the value
Err(E), // error and a description
}
let a: Result<i32, _> = "42".parse::<i32>(); // Ok(42)
let b = "x".parse::<i32>(); // Err(ParseIntError)There are no exceptions; the error is visible right in the return type.
Converting the error
map_err changes the error type, map the success value. Converting to a message to show the user is a common use:
fn yas_oku(s: &str) -> Result<u8, String> {
s.trim()
.parse::<u8>()
.map_err(|e| format!("geçersiz yaş: {e}"))
}
println!("{:?}", yas_oku(" 30 ")); // Ok(30)
println!("{:?}", yas_oku("300")); // Err("geçersiz yaş: number too large to fit in target type")Practice Read an age
Write the function fn yas_oku(s: &str) -> Result<u8, String> above. Print the results for "30" and "abc" with {:?}, separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn yas_oku(s: &str) -> Result<u8, String> {
s.trim()
.parse::<u8>()
.map_err(|e| format!("geçersiz yaş: {e}"))
}
fn main() {
println!("{:?} {:?}", yas_oku("30"), yas_oku("abc"));
}Expected output
Ok(30) Err("geçersiz yaş: invalid digit found in string")
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How does a caller know a function can fail?
- Because its return type is Result<T, E> Correct answer
- By reading the docs
- By running it
- From a throws keyword
Explanation: The possibility of failure is in the signature, and the compiler wants the Result to be used (unused Result warning).
2 Change the error type
s.parse::<u8>().____(|e| format!("geçersiz: {e}"))
s.parse::<u8>().map_err(|e| format!("geçersiz: {e}"))
Explanation: map_err only transforms the value inside Err.
3 Expression and result
| Term | Meaning |
|---|---|
"42".parse::<i32>() |
Ok(42) |
"x".parse::<i32>() |
Err(..) |
Ok(2).map(|n| n * 3) |
Ok(6) |
"300".parse::<u8>() |
Err: too large |