CallBacks and Defer In Golang 2020
In This Article You will understand Callbacks and Defer keyword in golang.
Check This Previous blog post written by Sagar Jaybhay for better understanding.
- 1: https://sagarjaybhay.net/google-go-tutorial-by-sagar-jaybhay-blog-1/
- 2: https://sagarjaybhay.net/packages-and-golang-command-part-2/
- 3: https://sagarjaybhay.net/detail-datatypes-in-golang-you-should-know-2019/
- 4:https://sagarjaybhay.net/tutorial-go-language-constant-in-golang-2019/
- 5:https://sagarjaybhay.net/control-flow-statement-in-golang-2019/
- 6: https://sagarjaybhay.net/for-loop-in-golang-2019/
- 7: https://sagarjaybhay.net/closure-rune-in-golang-2019/
- 8: https://sagarjaybhay.net/simple-memory-address-pointers-in-golang-2019/
- 9: https://sagarjaybhay.net/function-syntax-and-example-golang-by-sagar-jaybhay-2020/
Callbacks in golang:
In golang callbacks means we are passing a function as an argument.
package main import "fmt" func main() { ts := filternumbers([]int{10, 20, 30, 40}, func(n int) bool { return n > 10 }) fmt.Println(ts) } func filternumbers(numbers []int, callback func(int) bool) []int { ts := []int{} for _, n := range numbers { if callback(n) { ts = append(ts, n) } } return ts }

Defer keyword in golang:
It defers the execution of a function until its surrounding function/ nearby returns. In simple words defer means delay the execution of this function whatever we called.
Defer calls are put into a stack and when surrounding function return the call in a stack is picked up and execute that call.
If you pass any arguments to defer called function these arguments are evaluated at that time but the function is called when nearby function executed.
package main import "fmt" func main() { defer hellowword() hello() //fmt.Println("i m here for defer keyword") } func hello() { fmt.Println("i am in hello") } func hellowword() { fmt.Println("i am in hello world") }

Points to remember:
- Defer mainly used for clean-up actions.
- Multiple defer are allowed in the same program
- Arguments are evaluated at the time of the defer statement is executed.
- It used for cleaning work like to ensure the file is closed, a database connection is closed like that.
GitHub Project Link :- https://github.com/Sagar-Jaybhay/GoLanguageLab