"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > In Go language, the reasons and functions of using `()` after the `defer` statement

In Go language, the reasons and functions of using `()` after the `defer` statement

Posted on 2025-04-21
Browse:760

Why Use

The Rationale Behind "( )" in Closure Bodies in Go

In Go, the addition of "( )" after a closure body is not specific to closures but rather applies to any function call within a defer statement. The language specifications mandate that the expression in a defer statement must always be a function call.

Consider the example:

defer f()

This expression attempts to defer the execution of the function f itself, which does not make sense. Instead, the correct syntax is:

defer f()()

This constructs a closure that captures the current context and executes the function f when the defer statement is activated. The outer parentheses execute the closure immediately, ensuring that the function call takes place after the defer statement is executed.

This syntax is consistent with the general usage of function calls in Go, which always require parentheses to execute them. For instance, to print the value of i at the time the closure is defined, use the following syntax:

defer func(n int) { fmt.Println(n) }(i)

Conversely, to print the value of i at the time the closure is executed, use:

defer func() { fmt.Println(i) }()

Understanding this principle allows for clear comprehension of the behavior of defer statements in Go and the correct usage of "( )" within closure bodies and beyond.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3