Jacob Rosenthal brings you on a journey through options and results and when to use each, and to combine and chain them.

Options and Results via @jacobRosenthal

Ok and Err and Some and None Generally dont unwrap() or expect(). Rust is trying to help you write programs that don't exit randomly while running afterall!

return it

One option is to make it someone elses problem by just returning the result. We used to use try! macro Nowadays we cant use the try operator though, it has been replaced with the ?

deal with it yourself

Or you can deal with it yourself

match result {
    Some(x) => println!("Result: {}", x),
    None    => println!("Cannot divide by 0"),
}
if let Some(i) = number {
    println!("Matched {:?}!", i);
}
  • if you dont care about the value or error just the end (little case r) result try is_ok() or is_err()
if(x.is_ok() && y.is_err()){
}
  • you can also use Combinators to string a bunch of results or options together. Theres a TON of these
s1.or(s2)
s1.or_else(|| Some("some2"))
s1.and_then(|| Some("some2"))

Iterators

Iterators are another spot you're going to deal with options and results quite a bit. iter.next() returns an option. Though for looping calls iter.next for you and will handle it for you. But then you end up dealing with nested results and options quite a bit too. Check out all the Functional Combinators you may have heard of like filters, map/reduce

Crates you should know bluetooth edition:

  • rumble for scanning for ble devices and connecting to them
  • bluster for making a ble device for other people to connect to. Has no docs, but check out this bleboard implementation