Go defer

Introduction

Go defer runs a function after the function completes.

Consider the following example:

package main/* w  w  w  .j  a  v  a  2 s. com*/

import "fmt" 

func first() { 
    fmt.Println("1st") 
} 

func second() { 
    fmt.Println("2nd") 
} 

func main() { 
    defer second() 
    first() 
} 

This program prints 1st followed by 2nd.

Basically, defer moves the call to second to the end of the function:

func main() { 
    first() 
    second() 
} 

defer is often used when resources need to be freed in some way.

For example, when we open a file, we need to make sure to close it later. With defer:

f, _  := os.Open(filename) 
defer f.Close() 



PreviousNext

Related