Trusted answers to developer questions

Options in Rust

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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()
});
}

RELATED TAGS

option
enum
rust
some
none

CONTRIBUTOR

Anusheh Zohair Mustafeez
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?