【转】Options in Rust
原文:https://www.educative.io/edpresso/options-in-rust
--------------------------------
The Option enum in Rust can cater to two variants:
None: represents a lack of value or if an error is encounteredSome(value): value with typeTwrapped in a tuple
Code
Let’s look at a case where the Option enum could come in handy. The work_experience function below uses a match operator to return either values or a None object based on a person’s occupation.
fn work_experience(occupation: &str) -> Option{ match occupation{ "Junior Developer" => Some(5), "Senior Developer" => Some(10), "Project Manager" => Some(15), _ => None } } fn main() { println!("Years of work experience for a junior developer: {}", match work_experience("Junior Developer"){ Some(opt) => format!("{} years", opt), None => "0 years".to_string() }); println!("\nYears of work experience for a student: {}", match work_experience("Student"){ Some(opt) => format!("{} years", opt), None => "0 years".to_string() }); }