Nyx by Example

Defer and Cleanup

defer schedules a block of code to run when the enclosing function returns — regardless of which return statement is taken or whether an error occurs. It is the idiomatic way to guarantee cleanup of resources such as file handles, network connections, or locks.

Code

// defer: garantizar cleanup al salir del bloque, como file_close

fn main() -> int {
    let path: String = "/tmp/nyx_example_36.txt"
    let contenido: String = "Linea 1: Nyx defer example\nLinea 2: cleanup garantizado\n"

    // Escribir el archivo primero
    write_file(path, contenido)
    print("Archivo escrito: " + path)

    // Abrir el archivo con file_open
    let f: File = file_open(path, "r")

    // defer garantiza que file_close se ejecuta al salir,
    // sin importar si hay return temprano o error
    defer { file_close(f) }

    // Leer e imprimir el contenido
    let linea1: String = file_read_line(f)
    print("Leyendo: " + linea1)

    let linea2: String = file_read_line(f)
    print("Leyendo: " + linea2)

    print("El file_close se ejecutara automaticamente al salir")
    // file_close(f) es llamado aqui por defer

    return 0
}

Output

Archivo escrito: /tmp/nyx_example_36.txt
Leyendo: Linea 1: Nyx defer example
Leyendo: Linea 2: cleanup garantizado
El file_close se ejecutara automaticamente al salir

Explanation

defer { file_close(f) } registers the block immediately after the file is opened, but the block itself does not execute until the function is about to return. This ensures the file is closed no matter how the function exits — through the normal return 0, an early return, or an uncaught error.

In Nyx, defer always requires a block delimited by { } — bare expressions such as defer file_close(f) are not valid. Multiple deferred blocks in the same function execute in reverse registration order (last-in, first-out), mirroring how stack unwinding works.

This pattern is directly inspired by Go's defer and eliminates entire classes of resource-leak bugs that are common when cleanup must be placed at every possible exit point.

← Previous Next →

Source: examples/by-example/36-defer-cleanup.nx