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.

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
}

Callbacks in golang
Callbacks in golang

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")
}

Defer Keyword In golang
Defer Keyword In golang

Points to remember:

  1. Defer mainly used for clean-up actions.
  2. Multiple defer are allowed in the same program
  3. Arguments are evaluated at the time of the defer statement is executed.
  4. 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

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer at Software Company. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Sagar Jaybhay

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer at Software Company. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

You may also like...