Welcome To Golang By Example

Defer a goroutine in Go (Golang)

Table of Contents

Overview

It is not directly possible to defer a goroutine. But there is a workaround. In the defer function you can call another function in a goroutine like below

defer func() {
        go some_function()
}()

Example

Let’s see a program for it

package main
import (
    "fmt"
    "time"
)
func main() {
    call()
    time.Sleep(time.Second * 2)
}
func call() {
    defer func() {
        go test()
    }()
    fmt.Println("In call function")
}
func test() {
    fmt.Println("In test function")
}

Output

In call function
In test function

See how we indirectly defer a goroutine in the call function

defer func() {
        go test()
}()