Nyx by Example

Option: Some and None

Option<T> is Nyx's way of expressing a value that may or may not be present. Instead of returning a sentinel value like -1 or risking a null pointer, functions return Option.Some(value) on success or Option.None when there is nothing to return.

Code

// Option: función que retorna Some o None, match exhaustivo para manejar ambos

fn find_positive(nums: Array, index: int) -> Option<int> {
    let val: int = nums[index]
    if val > 0 {
        return Option.Some(val)
    }
    return Option.None
}

fn describe(opt: Option<int>) -> String {
    return match opt {
        Option.Some(v) => "encontrado: " + int_to_string(v),
        Option.None    => "no encontrado"
    }
}

fn main() -> int {
    let nums: Array = [10, -5, 3, -1, 7]

    // Caso Some: index 0 es positivo
    let a: Option<int> = find_positive(nums, 0)
    print(describe(a))

    // Caso None: index 1 es negativo
    let b: Option<int> = find_positive(nums, 1)
    print(describe(b))

    // if let para extraer el valor directamente
    let c: Option<int> = find_positive(nums, 4)
    if let Option.Some(v) = c {
        print("if let Some: valor es " + int_to_string(v))
    } else {
        print("if let: ningun valor")
    }

    return 0
}

Output

encontrado: 10
no encontrado
if let Some: valor es 7

Explanation

Option<T> is a generic enum with two variants: Option.Some(value) wraps an existing value of type T, and Option.None signals absence. Because it is part of the prelude, you do not need to import it — it is always available. This pattern eliminates an entire class of null-related bugs by making optionality explicit in the type system.

The describe function shows exhaustive match on an Option. The compiler requires both arms to be handled — forgetting Option.None is a compile-time error. The Some arm uses pattern destructuring to bind the inner value directly to v, which is then available in the arm's expression.

if let Option.Some(v) = c is a concise shorthand for when you only care about the Some case and want to fall through to an else branch for None. It binds v in the if-body without the ceremony of a full match expression.

← Previous Next →

Source: examples/by-example/24-option-some-none.nx