Hi, I’m Mingo.

In their learning Golang this time, I wrote a detailed study notes on my personal number WeChat public Go programming time, for the language, I was a beginner, so writing should fit in with the new to classmates, if you are just learning the language, don’t focus on prevention, study together, Grow together.

My Github:github.com/iswbm/GolangCodingTime my online blog: golang.iswbm.com


The process control methods in Go are still quite rich, and there are as follows:

  • If-else condition statement
  • Switch-case select statement
  • For-range loop statement
  • Goto Unconditional jump statement
  • Defer execution

Today is the last article on control flow, the defer statement, which I don’t see in other programming languages. It should be a keyword unique to the Go language, but even so, after reading this article, you can see how defer echoes in other programming languages.

1. Delay the call

The use of defer is simple, as it is simply followed by a function call to defer the XXX function call until the current function has finished executing.

defer xxx() Copy the code

This is a simple example that will quickly help you understand how defer works.

import "fmt"

func myfunc() {
    fmt.Println("B")
}

func main() {
    defer myfunc()
    fmt.Println("A")
}Copy the code

The output is as follows

A
BCopy the code

Of course, the above example can be abbreviated as the following, and the output is consistent

import "fmt"

func main() {
    defer fmt.Println("B")
    fmt.Println("A")
}Copy the code

2. Instant evaluated variable snapshot

Using defer is just a delay in calling the function, and the variables passed to the function should not be affected by subsequent programs.

Take this example right here

Import "FMT" func main() {name := "go" defer fmt.println (name) // Go name = "python" fmt.println (name) // python }Copy the code

As you can see from the output, name was reassigned to Python, and subsequent calls to defer still used the unreassigned variable values, as if all of this had been taken as a snapshot here.

python
goCopy the code

3. Multiple defer calls in reverse order

When we use multiple defers in a function, what are the execution functions for those defers?

Just do an experiment to find out

Import "FMT" func main() {name := "go" defer fmt.println (name) Go name = "python" defer fmt.println (name) // Output: python name = "Java" fmt.println (name)}Copy the code

As you can see from the output below, multiple deferred are called in reverse order, sort of like stacks, last in, first out.

java
python
goCopy the code

3. Which comes first, defer or return

At this point, defer is pretty understandable. In general use, there is no problem.

Here’s a slightly more complicated question: which one will defer or return be called first?

This can be easily observed using the following code

import "fmt" var name string = "go" func myfunc() string { defer func() { name = "python" }() fmt.Printf("myfunc Name: %s\n", name) return name} func main() {myname := myfunc() FMT.Printf("main name: = myfunc() FMT.Printf("main name: = myfunc() FMT.Printf("main name: = myfunc() FMT. %s\n", name) FMT.Println("main myname: ", myname)}Copy the code

The output is as follows

Myfunc myname: go main Myname: goCopy the code

So to understand this code, the first line is pretty straightforward, name is still a global variable, and the value is still go

The second line is also understandable, as we changed the global variable in defer, at which point the value of name has changed to Python

The important thing is the third line, why does it say go?

There is only one explanation, and that is that defer is called only after return. So before we defer, myName has been assigned to go.

4. Why defer?

After looking at the above example, I wonder if you are as familiar with the effect of this defer as I am? I’ve seen similar usage in Python.

While defer doesn’t exist in Python, it does have the with context manager. We know that we can use defer to manage resources in Python. The most common example is file opening and closing.

It doesn’t make any sense, you might wonder, as I would have just left the function that deferred executed at return.

Yes, but when there are multiple returns in a function, you have to call the function many times, and the code becomes bloated.

If you didn’t defer, you could write code like this

Func f() {r := getResource() //0, get the resource...... if ... {r.lease () //1, release resources return}...... if ... {r.lease () //2, release resources return}...... if ... {r.lease () //3, release resources return}...... R.lease () //4, release resources return}Copy the code

After you use defer, the code is straightforward and executes the function after defer no matter where you return.

Func f() {r := getResource() //0, get the resource defer r.ralase () //1, release the resource...... if ... {... return } ...... if ... {... return } ...... if ... {... return } ...... return }Copy the code

A series of reading

01. Setup of development environment (Goland & VS Code)

02. Learn five ways to create variables

03. Data type: **Integer and floating point **

Data types: byte, RUNe, and String

05. Data types: Array and slice

06. Data types: dictionary and Boolean

07. Data type: pointer

08. Object-oriented Programming: Structures and Inheritance

09. An article to understand the function in Go

10. Go language flow control: if-else conditional statements

11. Go language flow control: switch-case selection statement

12. Go language flow control: for loop statement

13. Go language flow control: GOto unconditional jump

14. Go language flow control: defer the call

15. Object-oriented programming: Interfaces and polymorphism

Key words: make and new difference?

17. An article to understand the blocks and scopes in Go

18. Learn Go coroutine: Goroutine

19. Learn Go coroutines: Detail channels/channels

20. Several classic error cases of channel deadlock

21. Learn the Go coroutine: WaitGroup

22. Learn Go coroutines: mutex and read-write locks

23. Exception handling in Go: Panic and recover

24. Super detailed interpretation of Go Modules past life and the introduction to use

25. Go language about package import must learn 8 knowledge points

26. How to open source your modules for others to use?

27. What about type assertions in Go?

28. These five points will help you understand the select usage of Go