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, andSome(value)
, a tuple struct that wraps a value with typeT
.
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 | fn exam_result(score: i32) -> Option<bool> { |
I hope the blog helps you understand the unfamiliar but brilliant concept of Rust. Enjoy coding =)