std/result

Result<T> is the standard type for error handling in Zen-C. It represents either success (Ok) containing a value of type T, or failure (Err) containing a string error message.

Overview

Usage

import "std/result.zc"
import "std/io.zc"

fn divide(a: int, b: int) -> Result<int> {
    if (b == 0) {
        return Result<int>::Err("Division by zero");
    }
    return Result<int>::Ok(a / b);
}

fn main() {
    match divide(10, 0) {
        Ok(val) => { println(f"Result: {val}"); },
        Err(e)  => { println(f"Error: {e}"); }
    }
}

Struct Definition

struct Result<T> {
    is_ok: bool;
    val: T;
    err: char*;
}

Methods

Construction

MethodSignatureDescription
OkResult<T>::Ok(v: T) -> Result<T>Creates a success result containing v.
ErrResult<T>::Err(e: char*) -> Result<T>Creates an error result with message e.

Query

MethodSignatureDescription
is_okis_ok(self) -> boolReturns true if the result is Ok.
is_erris_err(self) -> boolReturns true if the result is Err.
is_ok_andis_ok_and(self, f: fn(T) -> bool) -> boolReturns true when Ok and f accepts the contained value.
is_err_andis_err_and(self, f: fn(char*) -> bool) -> boolReturns true when Err and f accepts the error message.

Extraction

MethodSignatureDescription
unwrapunwrap(self) -> TReturns the ok value. Panics with the error message if Err.
unwrap_refunwrap_ref(self) -> T*Returns a pointer to the ok value. Panics if Err.
expectexpect(self, msg: char*) -> TReturns the value or panics with msg and the error message if Err.
unwrap_orunwrap_or(self, def: T) -> TReturns the ok value or def when Err.
unwrap_or_elseunwrap_or_else(self, f: fn() -> T) -> TReturns the ok value or the result of f when Err.
expect_errexpect_err(self, msg: char*) -> char*Returns the error message, or panics with msg when Ok.

Conversion

MethodSignatureDescription
okok(self) -> Option<T>Converts to an Option, mapping Ok to Some and discarding the error.
errerr(self) -> Option<char*>Converts to an Option holding the error message, when Err.
map_errmap_err(self, f: fn(char*) -> char*) -> Result<T>Applies f to the error message, leaving the value untouched.

Memory Management

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