docs / Getting Started / Option Types

Option Types

Option types represent values that may or may not be present. Add ? to any type to make it optional. The compiler prevents using option values without checking first — eliminating null pointer errors at compile time.

use system.io

// Option type: might be absent
let x int? = None
let y int? = 42

// Unwrap with if let
if let Some(val) = y
    println(f"y is {val}")

// Pattern matching
match x
    Some(n): println(f"got {n}")
    None: println("x is empty")

// Coalesce with ??
let safe = x ?? 0
println(f"safe: {safe}")

Three ways to handle option types:

  • if let Some(x) = val — unwrap and use in a block
  • match — handle Some and None branches
  • val ?? default — coalesce to a default value