SPECTRALANG_

// DOCS NAVIGATION

Operador de Propagação de Erro ?_

SOURCE: content/docs/reference/04-avancado.md04 Avançado / 5. Operador de Propagação de Erro ? / Error Propagation Operator ?

PT-BR:
O operador ? é uma forma concisa de propagar erros. Quando aplicado a um Result ou Option, ele desembrulha o valor se for Ok/Some, ou retorna antecipadamente da função com o Err/None se for o caso.

EN-US:
The ? operator is a concise way to propagate errors. When applied to a Result or Option, it unwraps the value if Ok/Some, or early-returns from the function with the Err/None otherwise.

func processar_entrada(entrada: string) returns Result<int, string> {
    // Sem o operador ? / Without the ? operator
    let r = analisar_inteiro(entrada)
    let n = match r {
        when Result::Ok(v) then v,
        when Result::Err(msg) then return Result::Err(msg)    // Propagação manual
    }
    return Result::Ok(n * 2)
}

func processar_entrada_conciso(entrada: string) returns Result<int, string> {
    // Com o operador ? / With the ? operator
    let n = analisar_inteiro(entrada)?
    // Propaga o erro automaticamente
    return Result::Ok(n * 2)
}

Nota / Note: A função que usa ? deve ter retorno compatível com o tipo sendo propagado (Result<T, E>Result<U, E>).

// Encadeamento elegante com ? / Elegant chaining with ?
func calcular_pipeline(a: string, b: string) returns Result<int, string> {
    let x = analisar_inteiro(a)?
    let y = analisar_inteiro(b)?
    let resultado = dividir(x, y)?
    return Result::Ok(resultado)
}

public func main() {
    match calcular_pipeline("10", "2") {
        when Result::Ok(v) then println(f"Resultado: {v}"),   // "Resultado: 5"
        when Result::Err(e) then println(f"Erro: {e}")
    }

    match calcular_pipeline("10", "0") {
        when Result::Ok(v) then println(f"Resultado: {v}"),
        when Result::Err(e) then println(f"Erro: {e}")          // "Erro: divisão por zero"
    }
}