Standard library · Basics

option

A value that may or may not be there, without nulls and without magic numbers such as minus one.

import option
On this page
  1. Types
  2. Functions

Sometimes the answer from a function is "nothing": a search found no match, or a setting was never given. Returning minus one or an empty string for that is convenient, and later forgotten, and then it is a bug. Option<T> makes it explicit: either there is a value of type T, or there is not.

If the reason for the failure matters as well as its absence, result is the better fit.

Types

Option

struct Option<T>
A struct that keeps a value and a "present or not" flag side by side. Build one with Some or None, so that the two fields always agree.
NameTypeDescription
valueTThe value itself. When present is false this is the zero value of T and means nothing.
presentboolTrue when there is a value.
option-Option.salam
import option

func search(names: Vector<str>, wanted: str): option.Option<int>:
    each i, name in names:
        if name == wanted:
            ret option.Some(i)
        end
    end
    ret option.None()
end

func main:
    mut names := Vector {} as Vector<str>
    defer names.free()
    names.push("Ali")
    names.push("Maryam")
    found := search(names, "Maryam")
    missing := search(names, "Reza")
    println option.IsSome(found), option.IsNone(found), found.value, found.present
    println option.IsSome(missing), option.IsNone(missing)
    println option.Unwrap(found), option.Expect(found, "this should have been found")
    println option.UnwrapOr(missing, -1)
end
Outputtrue false 1 true false true 1 1 -1

Functions

Some

func Some<T>(x: T): Option<T>
Builds an option that holds a value.

The example for this item is shown with the ones above: option-Option.salam

None

func None<T>(): Option<T>
Builds an empty option. The type T comes from where the value is used, such as the return type of the function.

The example for this item is shown with the ones above: option-Option.salam

IsSome

func IsSome<T>(o: Option<T>): bool
Returns true when the option holds a value.

The example for this item is shown with the ones above: option-Option.salam

IsNone

func IsNone<T>(o: Option<T>): bool
Returns true when the option is empty.

The example for this item is shown with the ones above: option-Option.salam

UnwrapOr

func UnwrapOr<T>(o: Option<T>, fallback: T): T
Returns the value, or the default you supplied when the option is empty.

The example for this item is shown with the ones above: option-Option.salam

Unwrap

func Unwrap<T>(o: Option<T>): T
Returns the value. If the option is empty, the program stops.

The example for this item is shown with the ones above: option-Option.salam

Expect

func Expect<T>(o: Option<T>, msg: str): T
Like Unwrap, but stops with a message of your own when the option is empty; a good message makes the problem easy to find.

The example for this item is shown with the ones above: option-Option.salam