Rust has a very powerful tool to deal with Result and Option
Option
struct User {
name: String,
password: String,
email: Option<String>,
age: Option<u32>,
}
fn main() {
let u: User = User{
name: "Apollo".to_string(),
password: "12345".to_string(),
email: Some("[email protected]".to_string()),
age: None
};
// Note the above should be a good refresher of Option...
// Now for using if let to access email
if let Some(email) = u.email {
println!("{} has an email ({})", u.name.clone(), email);
} else {
println!("{} has no email", u.name.clone());
}
// An example of trying to get age
if let Some(age) = u.age {
println!("{} is {} years old", u.name.clone(), age);
} else {
println!("{} didn't provide their age", u.name.clone());
}
}
Result
This example is minified to only highlight the concept of using if let
on Result
.
This also should serve as a brief example of Result
impl Database {
fn get_user_by_id(id: u64) -> Result<User, ()> {
// ...
// Basically, code that would read from a "Database"
// Look for a "User" by id (Presumably the Primary Key)
// And return either the User structure Ok(u)
// Or error Err(())
}
}
fn main() {
let user: Result<User, ()> = Database.get_user_by_id(3);
if let Ok(user) = user {
// ^ User
// Now we've got access to the user whose id is 3
} else {
// Not found, so do something else (Create)
}
}