0%

Rust | What does "Some" mean?

I was confused when I saw the keyword “Some” in Rust at first. As it is a rare keyword in other languages, at least for C++ and Python, I hope this blog will help you understand the meaning of the keyword and the concept behind it.

Rust has one of the most strict compilers within all languages I’ve learned. It introduced some interesting concepts to move lots of runtime errors of other languages to compile stage. Though forming a steeper learning curve, those concepts indeed keep developers from writing potential runtime bugs carelessly. The “option” is just an example.

To explain the keyword in one sentence:

“Some” is an enum value of an “Option” object that represents the state of “not None”.

Ok, then what is an “Option”? I regard it as a Rustacean solution to the annoying, unexpected NullPointerException in other languages.

The official documentation says that:

The Option<T> enum has two variants:

  • None, to indicate failure or lack of value, and
  • Some(value), a tuple struct that wraps a value with type T.

In other words, Option forces developers to deal with None condition. If you do not handle potential None, you will not pass the compilation unless you call unwrap() on purpose.

The meaning of Some becomes clear now. It stores the exact value you expect in a standard, not-none condition. You should load the value from the enum Some before doing whatever you want.

I wrote a simple example below that may help you understand the concept better.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
fn exam_result(score: i32) -> Option<bool> {
if score < 0 || score > 100 {
None
} else if score < 60 {
Some(false)
} else {
Some(true)
}
}

fn main() {
let scores = vec![-10, 59, 98, 107];
for score in scores.iter() {
let score = score.to_owned();
let result = exam_result(score);
match result {
Some(pass) => {
if pass {
println!("Score {} pass the exam", score);
} else {
println!("Score {} fail the exam", score);
}
}
None => {
println!("Score {} is invalid", score);
}
}
}
}

I hope the blog helps you understand the unfamiliar but brilliant concept of Rust. Enjoy coding =)