Option struct
Last updated
Was this helpful?
Was this helpful?
fn get_username_by_id(id: u32) -> Option<String> { // 1.
match(id) {
1 => Some(String::from("Susan")), // 2.
2 => Some(String::from("John")), // 3.
_ => None // 4.
}
}fn get_username_by_id(id: u32) -> Option<String> {
match(id) {
1 => Some(String::from("Susan")),
2 => Some(String::from("John")),
_ => None
}
}
fn main() {
let user1 = get_username_by_id(1); // 1.
let user10 = get_username_by_id(10); // 2.
if (user1.is_some()) { // 3.
println!("User with id = 1 holds username {}", user1.unwrap())
}
if (user10.is_none()) { // 4.
println!("User with id = 10 does not exist")
}
}fn get_username_by_id(id: u32) -> Option<String> {
match(id) {
1 => Some(String::from("Susan")),
2 => Some(String::from("John")),
_ => None
}
}
fn main() {
let user1 = get_username_by_id(1);
let user10 = get_username_by_id(10);
match (&user1) {
Some(name) => println!("User with id = 1 holds username {}", &user1.unwrap()),
None => println!("No user with id = 1 found")
}
match (&user10) {
Some(name) => println!("User with id = 10 holds username {}", &user10.unwrap()),
None => println!("No user with id = 10 found")
}
}