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 ...

Get Go: Design Patterns for Real-World Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.