Option and Result
The types represent optional data:
fn main() {let numbers = vec![10, 20, 30];let first: Option<&i8> = numbers.first();println!("first: {first:?}");let idx: Result<usize, usize> = numbers.binary_search(&10);println!("idx: {idx:?}");}
Speaker Notes
OptionandResultare widely used not just in the standard library.Option<&T>has zero space overhead compared to&T.Resultis the standard type to implement error handling as we will see in a later course.binary_searchreturnsResult<usize, usize>.- If found,
Result::Okholds the index where the element is found. - Otherwise,
Result::Errcontains the index where such an element should be inserted.
- If found,
The Result enum is defined as follows:
enum Result<T, E> {
Ok(T),
Err(E),
}