std/option

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

Usage

import "std/option.zc"
import "std/io.zc"

fn main() {
    let val = Option<int>::Some(10);
    
    if (val.is_some()) {
        println(f"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.
is_some_andis_some_and(self, f: fn(T) -> bool) -> boolReturns true when Some and f accepts the contained value.
is_none_oris_none_or(self, f: fn(T) -> bool) -> boolReturns true when None, or when Some and f accepts the value.

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.
unwrap_or_elseunwrap_or_else(self, f: fn() -> T) -> TReturns the contained value or the result of f when None.
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.

Conversion

MethodSignatureDescription
filterfilter(self, f: fn(T) -> bool) -> Option<T>Keeps the value when Some and f accepts it, otherwise None.

Memory Management

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