Home > Backend Development > Golang > Why Use '( )' After Closure Bodies in Go's `defer` Statements?

Why Use '( )' After Closure Bodies in Go's `defer` Statements?

Barbara Streisand
Release: 2024-12-02 18:55:11
Original
702 people have browsed it

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()
Copy after login

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

defer f()()
Copy after login

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)
Copy after login

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

defer func() { fmt.Println(i) }()
Copy after login

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.

The above is the detailed content of Why Use '( )' After Closure Bodies in Go's `defer` Statements?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template