Nyx by Example

if let

if let is a compact pattern-matching construct that combines a conditional check and a binding in one expression. It is especially useful when you only care about one variant of an enum and want to avoid the verbosity of a full match.

Code

// if let: destructurar Option sin match completo

fn find_even(nums: Array, start: int) -> Option<int> {
    let len: int = nums.length()
    var i: int = start
    while i < len {
        let v: int = nums[i]
        if v % 2 == 0 {
            return Option.Some(v)
        }
        i = i + 1
    }
    return Option.None
}

fn main() -> int {
    let data: Array = [1, 3, 4, 7, 8, 10]

    // if let extrae el valor si es Some
    let a: Option<int> = find_even(data, 0)
    if let Option.Some(v) = a {
        print("primer par desde 0: " + int_to_string(v))
    } else {
        print("no hay pares")
    }

    // buscar desde índice 4 (8 y 10 son pares)
    let b: Option<int> = find_even(data, 4)
    if let Option.Some(v) = b {
        print("primer par desde 4: " + int_to_string(v))
    } else {
        print("no hay pares desde 4")
    }

    // Array sin pares: retorna None -> ejecuta else
    let odds: Array = [1, 3, 5, 7]
    let c: Option<int> = find_even(odds, 0)
    if let Option.Some(v) = c {
        print("par encontrado: " + int_to_string(v))
    } else {
        print("no hay pares en odds")
    }

    return 0
}

Output

primer par desde 0: 4
primer par desde 4: 8
no hay pares en odds

Explanation

find_even scans an array starting from a given index and returns the first even number wrapped in Option.Some, or Option.None if no even number is found. This is a typical pattern for search functions: the return type communicates "found or not found" through the type system rather than a magic sentinel value.

The syntax if let Option.Some(v) = a evaluates the pattern Option.Some(v) against the value a. If it matches, the inner value is bound to v and the if-body executes with v in scope. If the pattern does not match (i.e., the value is Option.None), the else branch runs instead. This is exactly equivalent to a two-arm match but fits more naturally into imperative-style code.

The third call uses a purely odd array to demonstrate the else branch being taken. Notice that each if let block introduces a fresh binding v scoped to that block — there is no risk of the binding from the first block leaking into the second or third.

← Previous Next →

Source: examples/by-example/27-if-let.nx