Skip to content

Add defer statement - #377

Merged
mattn merged 1 commit into
masterfrom
add-defer-statement
Jul 10, 2026
Merged

Add defer statement#377
mattn merged 1 commit into
masterfrom
add-defer-statement

Conversation

@mattn

@mattn mattn commented Jul 10, 2026

Copy link
Copy Markdown
Owner

Adds Go-style defer to the language. defer f(args) evaluates the function and arguments at the defer statement and runs the call when the surrounding function returns, in LIFO order. Deferred calls also run when the function exits with an error, and top-level defers run when the script ends. The return value is never changed by defers; an error from a deferred call is reported only when the body did not already fail.

Parser gets a DEFER token and four stmt rules mirroring go. The VM captures calls in a per-invocation defers slice on runInfoStruct and runs them after the body. No measurable overhead when defer is unused (geomean -0.5%, interleaved benchstat n=6).

func f() {
  defer println("world")
  defer println("hello")
  println("start")
}
f() // start, hello, world

Add Go-style defer to the language: defer f(args) evaluates the
function and its arguments at the defer statement and runs the call
when the surrounding function returns, in LIFO order. Deferred calls
also run when the function exits with an error, and at the top level
they run when the script ends.

An error raised by a deferred call becomes the function error unless
the body already failed. The function return value is never changed
by defers.
@mattn
mattn merged commit 5c7bed5 into master Jul 10, 2026
12 checks passed
@mattn
mattn deleted the add-defer-statement branch July 10, 2026 01:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant