std/option

March 14, 2026 ยท View on GitHub

Option<T> represents an optional value: every Option is either Some and contains a value, or None. It is commonly used to handle the absence of a value without resorting to null pointers.

Overview

  • Safe: Encourages explicit handling of the None case.
  • Generic: Can wrap any type T.
  • Zero-cost: Compiles down to a simple struct with a boolean flag.
  • Convenient: Provides many utility methods for unwrapping and transforming values.

Usage

import "std/option.zc"

fn main() {
    let val = Option<int>::Some(10);
    
    if (val.is_some()) {
        println "Value is {val.unwrap()}";
    }
    
    let empty = Option<int>::None();
    let x = empty.unwrap_or(0);
}

Struct Definition

struct Option<T> {
    is_some: bool;
    val: T;
}

Methods

Construction

MethodSignatureDescription
SomeOption<T>::Some(v: T) -> Option<T>Creates a Some option containing v.
NoneOption<T>::None() -> Option<T>Creates a None option.

Query

MethodSignatureDescription
is_someis_some(self) -> boolReturns true if the option is Some.
is_noneis_none(self) -> boolReturns true if the option is None.

Extraction

MethodSignatureDescription
unwrapunwrap(self) -> TReturns the contained value. Panics if None.
unwrap_refunwrap_ref(self) -> T*Returns a pointer to the contained value. Panics if None.
unwrap_orunwrap_or(self, def: T) -> TReturns the contained value or def.
expectexpect(self, msg: char*) -> TReturns the value or panics with msg.
or_elseor_else(self, other: Option<T>) -> Option<T>Returns the option if Some, otherwise returns other.

Memory Management

MethodSignatureDescription
forgetforget(self)Zeroes out the internal value without calling destructors or freeing memory.