O'Reilly logo

Go: Design Patterns for Real-World Projects by Mat Ryer, Mario Castro Contreras, Vladimir Vivien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Deferring function calls

Go supports the notion of deferring a function call. Placing the keyword defer before a function call has the interesting effect of pushing the function unto an internal stack, delaying its execution right before the enclosing function returns. To better explain this, let us start with the following simple program that illustrates the use of defer:

package main 
import "fmt" 
 
func do(steps ...string) { 
   defer fmt.Println("All done!") 
   for _, s := range steps { 
         defer fmt.Println(s) 
   } 
 
   fmt.Println("Starting") 
} 
 
func main() { 
   do( 
         "Find key", 
         "Aplly break", 
         "Put key in ignition", 
         "Start car", 
   ) 
} 

golang.fyi/ch05/defer1.go

The previous example defines the do function that takes variadic parameter steps. The function defers the statement ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required