CodeBlanks Logo Icon CodeBlanks

Option instead of null

Learn the advantages of Option over null.

Option instead of null

In other languages "not found" is often shown with null, -1 or an empty string, and bugs appear when the check is forgotten. In Rust every result that might be missing returns an Option, and the check becomes part of the type:

let meyveler = ["armut", "elma", "kiraz"];
let i = meyveler.iter().position(|m| *m == "elma");   // Some(1)
let j = meyveler.iter().position(|m| *m == "muz");    // None

That's why many methods such as Vec::get, str::find, HashMap::get and iter().max() return Option.

Chaining helpers

Methods that work on Option without writing a match shorten the code:

let sira = i.map(|n| n + 1);          // Some(2): position counting from 1
let varsay = j.unwrap_or(0);          // 0
let var_mi = i.is_some();             // true
let metin = j.map_or("yok".to_string(), |n| n.to_string());   // "yok"

map only transforms the value inside Some and leaves None as it is.

Practice Fruit position

Write fn bul(liste: &[&str], ad: &str) -> Option<usize> (iter().position). For ["armut", "elma", "kiraz"], compute bul(.., "elma").map(|i| i + 1).unwrap_or(0) and the same for "muz", and print them separated by a space.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn bul(liste: &[&str], ad: &str) -> Option<usize> {
    liste.iter().position(|m| *m == ad)
}

fn main() {
    let meyveler = ["armut", "elma", "kiraz"];
    let a = bul(&meyveler, "elma").map(|i| i + 1).unwrap_or(0);
    let b = bul(&meyveler, "muz").map(|i| i + 1).unwrap_or(0);
    println!("{} {}", a, b);
}

Expected output

2 0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>Vec::new::&lt;i32&gt;().iter().max()</code> return?

  • Some(0)
  • None Correct answer
  • 0
  • Panic

Explanation: An empty collection has no largest element; this is stated honestly with None.

2 Default value

Question
let j: Option<usize> = None;
let n = j.____(0);   // 0
Answer
let j: Option<usize> = None;
let n = j.unwrap_or(0);   // 0

Explanation: unwrap_or returns the given default when it is None.

3 Method and result on None

Term Meaning
is_some() false
unwrap_or(7) 7
map(|n| n + 1) None
unwrap() Panic

All lessons in Beginner