Sitemap
Learn Go Programming

Visual, concise and detailed tutorials, tips and tricks about Go (aka Golang).

Follow publication

Go Defer Simplified with Practical Visuals

5 min readNov 23, 2017

--

What is defer?

Zoom image will be displayed
Prints: “first” than “later”
Zoom image will be displayed
Zoom image will be displayed

Releasing acquired resources

Zoom image will be displayed

The func closes the opened file whether there is an error or not on all returns — marked with the star.

Save us from panic

Zoom image will be displayed
Zoom image will be displayed

Deferred closure

Zoom image will be displayed
Understand how a defer func sees its context

Params evaluation

Zoom image will be displayed

Example

func count(i int) (n int) {  defer func(i int) {
n = n + i
}(i)
i = i * 2
n = i
return
}

Let’s try:

count(10)// output: 30

What happened?

Zoom image will be displayed
Parse the visual following the numbers (on the left): 1, 2, 3.
Zoom image will be displayed

Multiple defers

Example

Zoom image will be displayed

Output

first
last
To understand how multiple defers work
Zoom image will be displayed

Watch how it works

Zoom image will be displayed
The animation loops

Deferred methods

Without pointers

type Car struct {
model string
}
func (c Car) PrintModel() {
fmt.Println(c.model)
}
func main() {
c := Car{model: "DeLorean DMC-12"}
defer c.PrintModel() c.model = "Chevrolet Impala"
}

Output

DeLorean DMC-12

With Pointers

func (c *Car) PrintModel() {
fmt.Println(c.model)
}

Output

Chevrolet Impala

What’s going on?

Zoom image will be displayed

Let’s stay in touch:

--

--

Learn Go Programming
Learn Go Programming

Published in Learn Go Programming

Visual, concise and detailed tutorials, tips and tricks about Go (aka Golang).

Inanc Gumus
Inanc Gumus

Written by Inanc Gumus

Coder. Gopher. Maker. Stoic. Since 1992.

Responses (3)