Browse documentation
Data structures

Result

Typed success or recoverable error outcomes, explicit checked access, native validation results, managed ownership and complexity.

Implemented

Result<T, E> is an import free typed outcome containing either a successful value of T or an error value of E. It lets a function report an expected recoverable outcome through its explicit return type.

Expected type factory construction and postfix propagation below require Aner 0.0.4 or newer built from this source. Earlier published binaries may require explicit factory type arguments and reject ?; match the executable to this documentation.

Construction and use

aner
fn divide(numerator: Float64, denominator: Float64) -> Result<Float64, String> {
    if denominator == 0.0 {
        return Result.err(error: "denominator is zero")
    }
    return Result.ok(value: numerator / denominator)
}
let outcome = divide(6.0, 2.0)
if outcome.is_ok() {
    print(outcome.unwrap())
} else {
    print(outcome.unwrap_err())
}

Result.ok<T, E>(value: T) creates a success. Result.err<T, E>(error: E) creates an error. Explicit arguments name both alternatives. If an expected Result<T, E> is supplied by an annotated binding, assignment, explicitly declared return, typed user function argument, declared class constructor field or wrapper unwrap_or fallback, the factories can omit both type arguments. Success and error payloads are checked against those known types, including Number and checked exact Float64 promotion for numeric payloads. A Number payload retains its concrete integer type, Float32, or Float64 representation; Float64 payloads accept integers only when exactly representable.

For example, let result: Result<Int64, String> = Result.ok(7) knows the error type from the annotation. Nested factories such as let result: Result<Optional<Int64>, String> = Result.ok(Optional.none()) use the complete expected payload type. Without a suitable expected Result, Result.ok(7) cannot invent E and Result.err("bad") cannot invent T; use explicit specializations in those contexts.

Success and error payloads may include scalar quantities or points after import aner.units. For example, Result<Quantity<m>, String> retains the exact meter type, and expected construction can use Result.ok(2.0@m). A centimeter payload requires explicit .to("m") conversion. Postfix propagation preserves its existing one layer and exact error type rules; it does not convert units or catch native unit/numeric diagnostics.

Unit bearing arrays can be success payloads with an exact nested type, such as Result<Array<Quantity<m>>, String>. Wrapping or propagating one retains its mutable array reference; it neither copies the buffer nor converts its element unit.

This is an explicit data contract. Returning an error Result does not throw a runtime exception, and Result does not automatically intercept native failures. A function must choose which expected conditions it represents as values. Unchecked access to the inactive alternative still produces a runtime error.

Propagate one Result layer

Postfix ? evaluates one Result once. On success, its expression value is the success payload. On error, it returns early from the immediately enclosing function, creating a new error wrapper with that function's declared Result type and preserving the error payload.

aner
fn observed_year(text: String) -> Result<Int64, String> {
    let date = Date.try_parse(text)?
    return Result.ok(date.year())
}
print(observed_year("2026-10-14").unwrap())
print(observed_year("2026-02-30").is_err())

This complete program prints 2026, then true. The inner success type is Date and the outer success type is Int64; both error types are exactly String. An error wrapper is re created once at each propagated function boundary, rather than reusing an incompatible Result<Date, String> wrapper as Result<Int64, String>. Reference error payloads keep their existing reference identity.

The enclosing function must have an explicit -> Result<T, E> annotation, and the operand's error type must match E exactly. ? is not supported at top level, in a Unit/scalar-returning function, on Optional, or inside a function whose Result return is only inferred. There is no automatic conversion between different error types, including promotion to Any.

Place ? on the same line as the operand's final token. A multiline call can use ? beside its closing ). read()\n? is rejected. Each marker unwraps only one layer; nested Results use an intermediate binding or explicit parentheses such as (nested?)?. Adjacent ??, even with separating spaces, is rejected. Calls, fields and brackets can continue after a successfully propagated payload.

Arguments and operands before the failing Result keep their completed effects. Remaining operands, call arguments and statements in that function are skipped. The operator does not catch native diagnostics, create a success automatically, or convert an error into missingness; a checked successful function still needs an explicit success return. Nullable class annotations such as Node? retain their existing type meaning.

Native recoverable conversion

Native Date.try_parse, Time.try_parse, DateTime.try_parse, and Duration.try_parse return a Result with their value type and String errors. Bytes.try_from_hex returns Result<Bytes, String>; bytes.try_decode_utf8() returns Result<String, String>. They apply the same strict validation as their failing conversion counterparts, and represent expected malformed input as the error alternative. Resource failures and unrelated runtime errors retain the ordinary execution contract.

aner
let observed = Date.try_parse("2026-02-30")
if observed.is_err() {
    print(observed.unwrap_err())
}

These factory names do not change the accepted input grammar or silently repair values.

Methods

MethodResultContract
is_ok()BoolWhether the active alternative is success.
is_err()BoolWhether the active alternative is error.
unwrap()TReturn success, or fail when the active alternative is error.
unwrap_err()EReturn error, or fail when the active alternative is success.
unwrap_or(default: T)TReturn success, otherwise the supplied same type default.

These methods retain explicit checked access after a condition. unwrap_or evaluates its default expression under ordinary call rules even when the Result succeeds. Postfix ? provides the explicit Result only propagation described above. Automatic exception conversion, pattern matching and lazy error callbacks remain unavailable.

Ownership and identity

The immutable managed wrapper owns one active payload slot and traces reference payloads through the shared execution heap. Copies retain wrapper identity. Class and mutable collection payloads keep their existing reference semantics; Result does not deep copy or freeze them. Nested Result and Optional values are permitted, subject to the ordinary static type and heap limits.

Equality compares wrapper identity rather than recursively comparing the active payload. Distinct factories create distinct wrappers. Compare unwrap() or unwrap_err() explicitly after checking the active alternative when value comparison is intended. Result is not an accepted scalar Dictionary key or Set member.

type(value) reports a concrete specialization such as Result<Float64, String>. Checked casts from Any require the same T and E. dtype is unsupported: an outcome descriptor does not supply a homogeneous storage datatype. There is no implicit success/error-to-Bool conversion.

Errors and limits

Unchecked access to an inactive alternative or a wrapper operation limit failure produces a located runtime error R3404. Wrong static argument types or arities produce E1002. Generic wrapper nesting is limited to 128 and formatted type names to 16 KiB; exceeding these static bounds produces E1007. Shared managed object and value slot limits also apply. A runtime failure retains the normal program or persistent session error contract.

Propagation adds one checked wrapper access on success. On error, the enclosing boundary constructs one new wrapper, with the ordinary descriptor/payload ownership and allocation costs. It is an early return mechanism, not a transaction: completed external effects are not reversed.

Time and space complexity

The wrapper uses O(1) active state metadata and one active payload slot, plus a generic type descriptor. Materializing or copying a descriptor of size g adds O(g) time and space at construction or value copy boundaries. Branch tests and identity equality perform O(1) active state work plus O(g) receiver descriptor validation at the heap boundary; checked access adds that validation and returned payload copy costs. Payload evaluation, owned value copying, and formatting add the payload's existing time and space costs. Reference payloads retain shared objects instead of duplicating them. Garbage collection follows the execution heap's normal reachable object and slot costs.

Run the complete Result example or the concise research syntax example, and see Optional for typed absence without an error alternative.

Aner documentation · Reference and guides