Tutorial by Examples

// The Option type can either contain Some value or None. fn find(value: i32, slice: &[i32]) -> Option<usize> { for (index, &element) in slice.iter().enumerate() { if element == value { // Return a value (wrapped in Some). return Some(index);...
fn main() { let maybe_cake = Some("Chocolate cake"); let not_cake = None; // The unwrap method retrieves the value from the Option // and panics if the value is None println!("{}", maybe_cake.unwrap()); // The expect method works much like the un...
A reference to an option &Option<T> cannot be unwrapped if the type T is not copyable. The solution is to change the option to &Option<&T> using as_ref(). Rust forbids transferring of ownership of objects while the objects are borrowed. When the Option itself is borrowed (&a...
The map operation is a useful tool when working with arrays and vectors, but it can also be used to deal with Option values in a functional way. fn main() { // We start with an Option value (Option<i32> in this case). let some_number = Some(9); // Let's do some consecutive ...

Page 1 of 1