
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")
}
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")
}
Important:
for i := 0; i < 10; i++ {
defer fmt.Println(i)
}
output:
counting
done
9
8
7
6
5
4
3
2
1
0
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
Comments
Join the discussionNo comments yet. Be the first to comment.



