11.3. defer and defer_delete macros

The DEFER module implements the defer pattern — the ability to schedule cleanup code to run at scope exit, similar to Go’s defer. The deferred block is moved to the finally section of the enclosing scope at compile time.

All functions and symbols are in “defer” module, use require to get access to it.

require daslib/defer

Example:

require daslib/defer

    [export]
    def main() {
        print("start\n")
        defer() {
            print("cleanup runs last\n")
        }
        print("middle\n")
    }
    // output:
    // start
    // middle
    // cleanup runs last

11.3.1. Function annotations

defer::DeferMacro

This macro converts defer() <| block expression into {}, and move block to the finally section of the current block

11.3.2. Call macros

defer::defer_delete

This macro converts defer_delete() expression into {}, and add delete expression to the finally section of the current block

11.3.3. Defer

defer::defer(blk: block<():void>)

defer a block of code. For example:

var a = fopen("filename.txt","r")
defer <|
    fclose(a)

Will close the file when ‘a’ is out of scope.

Arguments
  • blk : block<void>

11.3.4. Stub

defer::nada()

helper function which does nothing and will be optimized out