Nyx by Example

Result: Ok and Err

Result is Nyx's idiomatic type for operations that can fail with an error message. A function returns Result.Ok(value) when it succeeds and Result.Err(message) when something goes wrong — making error handling explicit and impossible to accidentally ignore.

Code

// Result: función que retorna Ok o Err, match exhaustivo para manejar ambos

enum Result {
    Ok(int),
    Err(String)
}

fn safe_divide(a: int, b: int) -> Result {
    if b == 0 {
        return Result.Err("division por cero")
    }
    return Result.Ok(a / b)
}

fn safe_sqrt(n: int) -> Result {
    if n < 0 {
        return Result.Err("raiz de negativo")
    }
    var i: int = 0
    while i * i <= n {
        i = i + 1
    }
    return Result.Ok(i - 1)
}

fn describe(r: Result) -> String {
    return match r {
        Result.Ok(v)  => "ok: " + int_to_string(v),
        Result.Err(e) => "error: " + e
    }
}

fn main() -> int {
    let r1: Result = safe_divide(100, 4)
    print(describe(r1))

    let r2: Result = safe_divide(10, 0)
    print(describe(r2))

    let r3: Result = safe_sqrt(16)
    print(describe(r3))

    let r4: Result = safe_sqrt(-5)
    print(describe(r4))

    return 0
}

Output

ok: 25
error: division por cero
ok: 4
error: raiz de negativo

Explanation

Result is a regular enum with two variants. In this example it is defined locally with Ok(int) and Err(String), but in real Nyx programs you typically use the generic Result<T, E> from the prelude. Either way the pattern is identical: return one variant on success, the other on failure, and let the caller decide what to do.

safe_divide guards against division by zero before performing the operation. safe_sqrt uses a manual integer loop to compute floor square roots without floating-point arithmetic, returning an error for negative inputs. Both functions communicate failure through the type system rather than exceptions or out-of-band error codes.

The describe helper matches exhaustively on both variants. The compiler enforces that every variant is handled — if you add a third variant to the enum later, every existing match site becomes a compile error until you handle the new case. This exhaustiveness check is one of the most powerful safety properties of algebraic types.

← Previous Next →

Source: examples/by-example/25-result-ok-err.nx