What are Some and None?

The signature of get (for slices, not Vec, since you're using an array/slice) is

fn get(&self, index: usize) -> Option<&T>

That is, it returns an Option, which is an enum defined like

pub enum Option<T> {
    None,
    Some(T),
}

None and Some are the variants of the enum, that is, a value with type Option<T> can either be a None, or it can be a Some containing a value of type T. You can create the Option enum using the variants as well:

let foo = Some(42);
let bar = None;

This is the same as the core data Maybe a = Nothing | Just a type in Haskell; both represent an optional value, it's either there (Some/Just), or it's not (None/Nothing).

These types are often used to represent failure when there's only one possibility for why something failed, for example, .get uses Option to give type-safe bounds-checked array access: it returns None (i.e. no data) when the index is out of bounds, otherwise it returns a Some containing the requested pointer.

See also:

  • Why don't Option's Some and None variants need to be qualified?
  • What is the difference between Some and Option in Rust?

Think of Some and None as the canonical "safe" way of working around the fact that the Rust language does not support "safe" use of NULL pointers. Since the length of your Vec is 3, and you have only specified two pairs, the third pair is effectively NULL; instead of returning NULL, it returns None.

Rust provides safety guarantees by forcing us at compile-time, via Some / None, to always deal with the possibility of None being returned.

Tags:

Optional

Rust