Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Defer a goroutine in Go (Golang)

Posted on September 20, 2020September 20, 2020 by admin

Table of Contents

  • Overview
  • Example

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()
}()
  • go
  • golang
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme