typestar

Optional values in Mojo

Optional models a result that may not be there at all.

def first_even(values: List[Int]) -> Optional[Int]:
    for value in values:
        if value % 2 == 0:
            return value
    return None

def main():
    var found = first_even([3, 5, 8, 9])
    if found:
        print("first even:", found.value())
    var missing = first_even([1, 3, 5])
    print("found anything:", Bool(missing))

How it works

  1. first_even returns an Int on success and None otherwise.
  2. An Optional is truthy when it holds something, so if found: works.
  3. value() unwraps it once that check has passed.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
288
Tokens
81
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 6 of 6 in Collections, step 17 of 26 in Language basics.

← Previous Next →