- Result type
- Option type
- What to do with Result or Option
- Success: use the value
- Failure: recover
- Recoverable => Unrecoverable
testing methods
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
fn main() {
let v = Version{
id: 123,
published_by: Some(12),
};
let u = v.published_by();
println!("{:?}", u);
}
#[derive(Debug)]
struct Version {
id: i32,
published_by: Option<i32>,
}
#[derive(Debug)]
struct User {
id: i32,
login: String,
}
impl User {
fn find(id: i32) -> Self {
User {
id: 1,
login: String::from("hello")
}
}
}
impl Version {
pub fn published_by(&self) -> Option<User> {
self.published_by.map(|p| User::find(p))
}
}