Skip to main content

Stacking defers

Updated 1 min readMarkdown
Part of series GopherLabs
Stacking defers

Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.

lets write a program to count numbers from 1 to 9

package main

import "fmt"

func main() {
    fmt.Println("counting")

    for i := 0; i < 10; i++ {
         fmt.Println(i)
    }

    fmt.Println("done")
}

Go Playground

Stacking defers - use defer defer fmt.Println(i). because of defer its give you output of last result in first thats known as last-in-first out manner

package main

import "fmt"

func main() {
    fmt.Println("counting")

    for i := 0; i < 10; i++ {
         defer fmt.Println(i)
    }

    fmt.Println("done")
}

Go Playground

Important:

    for i := 0; i < 10; i++ {
         defer fmt.Println(i)
    }

output:

counting
done
9
8
7
6
5
4
3
2
1
0

14 views

About the author

  • DevRel at StackGen | Formerly at Deepfence ,Tenable , Accurics | AWS Community Builder also Docker Community Award Winner at Dockercon2020 | CyberSecurity Innovator of Year 2023 award by Bsides Bangalore | Docker/HashiCorp Meetup Organiser Bangalore & Co-Author of Learn Lightweight Kubernetes with k3s (2019) , Packt Publication & also run Non Profit CloudNativeFolks / CloudSecCorner Community To Empower Free Education reach out me twitterhttps://twitter.com/sangamtwts or just follow on GitHub -> https://github.com/sangam14 for Valuable Resources

No comments yet. Be the first to comment.

GopherLabs

Part 1 of 50

Ultimate Series of Blogs for All Golang Developer

More from this blog