Saltar al contenido

08 · Manejo de Errores

Cuerpos de funciones falibles

Una función que devuelve T fails E expone Result<T, E> al llamador. Devuelve los valores exitosos directamente; fail error sale con Err. El operador ? propaga el fallo hasta el límite Result más cercano, incluido un bloque attempt local.

En esta página

Una función que devuelve T fails E expone Result<T, E> al llamador. Devuelve los valores exitosos directamente; fail error sale con Err. El operador ? propaga el fallo hasta el límite Result más cercano, incluido un bloque attempt local.

Ejemplo completo

Cuerpos de funciones falibles.

fallible_invoice.zolo
Playground
// An invoice rejects missing stock and exposes Result<int, str> to its caller.
fn subtotal(quantity: int, unit_price: int) -> int fails str {
    if quantity <= 0 { fail "quantity must be positive" }
    if unit_price < 0 { fail "price cannot be negative" }
    quantity * unit_price
}

fn invoice(quantity: int, unit_price: int) -> int fails str {
    let total = subtotal(quantity, unit_price)?
    total + 12
}

match invoice(3, 25) {
    .Ok(total) => print("Invoice: {total}"),
    .Err(message) => print("Cannot create invoice: {message}"),
}

Referencia

Referencia · Programa fuente

zolo run examples/features/fallible_invoice.zolo --no-cache

Consulta también

Índice global

Encuentra tu camino por Zolo

Prueba una idea

Empieza aquí

9 resultados

9 resultados

enespt-br