A Rust operation that might fail can return a Result. It holds either an Ok value for success or an Err value for failure. Use Option instead when a value might simply be absent and that absence is not an error. section 5.2 section 5.2.2
enum Option<T> {
None,
Some(T),
}
enum Result<T, E> {
Ok(T),
Err(E),
}
The enum definition shows the two possible variants. In Result<T, E>, T is the type inside Ok and E is the type inside Err; they can be different types. section 5.2.2
An Err value can say what went wrong. For example, a function expecting the number 5 can return Ok(5) for a match and an Err containing a message for any other number. A String is enough to start with; it does not have to be a formal error type. section 5.2.2 section 5.3
fn check_if_five(number: i32) -> Result<i32, String> {
match number {
5 => Ok(number),
_ => Err(format!("Sorry, bad number. Expected: 5 Got: {number}")),
}
}
fn main() {
for number in 4..=7 {
println!("{:?}", check_if_five(number));
}
}
Follow each arm of match: one returns the number in Ok; the other builds a message in Err. The loop lets you see both outcomes. section 5.2.2
Do not ignore a returned Result. The compiler warns that even a function returning Result<(), ()> could have produced Err. Check the outcome and decide what to do: .is_ok() and .is_err() test which variant you have. Calling .unwrap() on Err instead causes a panic. section 5.2.2
warning: unused `std::result::Result` that must be used --> src\main.rs:6:5 | 6 | check_error(); | ^^^^^^^^^^^^^^ | = note: `#[warn(unused_must_use)]` on by default = note: this `Result` may be an `Err` variant, which should be handled
The warning points to a Result that was returned but never checked. Treat it as a prompt to handle the possible error. section 5.2.2
Result is common in file and directory operations: a file might not exist or might be inaccessible. The ? operator is handy when working with such operations. A task can also combine Result and Option—for example, connecting to a server may fail, while a successful connection may have no data. section 18.3 section 5.2.2







