Welcome To Golang By Example

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

Can defer be used inside main function in Go (Golang)

Posted on September 23, 2020September 23, 2020 by admin

Table of Contents

  • Overview
  • Example

Overview

Defer as the name suggests is used to defer the cleanup activities in a function. These cleanup activities will be performed at the end of the function.

defer can be used inside the main function as well. Let’s see an example for that

Example

package main
import "fmt"
func main() {
    defer test()
    fmt.Println("Executed in main")
}
func test() {
    fmt.Println("In Defer")
}

Output

Executed in main
In Defer

In the above program there is a defer statement calling the custom function named test. As seen from the output, the test function is called after everything in the main is executed and before main returns. That is why

Executed in main

is printed before

In Defer

The above function also that it is perfectly ok to use defer in the main function as well.

  • 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