• Result type
  • Option type
  • What to do with Result or Option
    • Success: use the value
    • Failure: recover
  • Recoverable => Unrecoverable

testing methods

  • Result
    • is_ok
    • is_err
  • Option
    • is_some
    • is_none

Result to Option

  • ok method
    • Ok(T).ok() -> Some(T)
    • Err(E).ok() -> None

Option to Result

  • ok_or method
    • Some(T).ok_or(err_value) -> Ok(T)
    • None.ok_or(err_value) -> Err(err_value)

fallback

  • Ok(T).unwrap_or(fallback) -> T
  • Some(T).unwrap_or(fallback) -> T
  • Err(E).unwrap_or(fallback) -> fallback
  • None.unwrap_or(fallback) -> fallback

unwrap_or_default

  • calls the default function from the Default trait

Transform Ok or Some values only

  • Ok(T).map(|v| v.operation()) -> T.operation()
  • Some(T).map(|v| v.operation()) -> T.operation()
  • Err(E).map(…) -> Err(E)
  • None.map(…) -> None
  1. fn main() {
  2. let v = Version{
  3. id: 123,
  4. published_by: Some(12),
  5. };
  6. let u = v.published_by();
  7. println!("{:?}", u);
  8. }
  9. #[derive(Debug)]
  10. struct Version {
  11. id: i32,
  12. published_by: Option<i32>,
  13. }
  14. #[derive(Debug)]
  15. struct User {
  16. id: i32,
  17. login: String,
  18. }
  19. impl User {
  20. fn find(id: i32) -> Self {
  21. User {
  22. id: 1,
  23. login: String::from("hello")
  24. }
  25. }
  26. }
  27. impl Version {
  28. pub fn published_by(&self) -> Option<User> {
  29. self.published_by.map(|p| User::find(p))
  30. }
  31. }