Options in Rust

The Option<T> enum in Rust can cater to two variants:

  • None: represents a lack of value or if an error is encountered
  • Some(value): value with type T wrapped in a tuple
svg viewer

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<u32>{
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()
});
}
Copyright ©2024 Educative, Inc. All rights reserved