70 %
Chris Biscardi

What is the Option Type in Rust

Option in Rust represents a value that may or may not be there: It is optional.

Consider the following example where we have some configuration for our program. This configuration lets the user set their favorite color.

rust
struct Config {
favorite_color: Option<String>
}
fn main() {
let config = Config {
favorite_color: Some("pink")
}
}

Now there are many reasons we might not have a value here yet. Maybe the user hasn't set a favorite color since it's their first time using the program. Maybe they don't even have a favorite color! So instead of using String as the type of favorite_color, we use Option<String>. This lets the user decided whether or not they want the program to know what their favorite color is.

rust
struct Config {
favorite_color: Option<String>
}
fn main() {
let config = Config {
favorite_color: None
}
}

In the first example the user's favorite color was "pink", and in the second example the user doesn't have one. These differences are represented by Some(value) and None.

You could combine this with env var configuration to enable different behaviors.