Self study series of golang (2)


Defer keyword

First of all, let’s look at the definition of the official website

A “defer” statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.

That is, the fragment marked with defer will call a function, which will be delayed after the execution of the surrounding functions. Note that panicking is also included in the final description. What is this?

After reading the official website document’s explanation of panicking, I think it is oneUnknown in runtimeAn exception handler, such as an array out of bounds, triggers a run-time panic. It is equivalent to calling the built-in function panic, and using the value of the interface type runtime error as the parameter. Triggering this error means that it is an undetermined error.

The format of the defer call is

Deferstmt = "defer" expression. // expression must be a method or function

There is a very important point

Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred.

Every time a defer statement is called, the values and parameters of this ordinary function will be changedResave, but it’s not actually called. Instead, it is called immediately before the return of the surrounding function, and the execution of the marked defer will be canceledReverse order recall

for instance:

// out func
func f() (result int) {
	defer func() {
		result *= 7
	return 6
for i := 0; i <= 3; i++ {
  defer fmt.Println(i)

Through the previous concepts and key points, we probably know what the output is. As a result, I won’t let it go. When you see this article, please try it yourself.

Recommended Today

Rust Study RoadMap

background In recent months, I began to learn rust, and began to write some code with rust. Now, I don’t have a deep understanding of rust, but it’s OK to write some code everyday, and I can learn the next step as needed. In the process of learning, the author also read a lot of […]