Welcome To Golang By Example

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

Inline Function in Defer in Go (Golang)

Posted on September 21, 2020September 21, 2020 by admin

Table of Contents

  • Overview
  • Example

Overview

It is also possible to have an inline function with defer.

Example

Let’s see an example of that.

package main

import "fmt"

func main() {
    defer func() { fmt.Println("In inline defer") }()
    fmt.Println("Executed")
}

Output

Executed
In inline defer

In the above code we have defer with a inline function

defer func() { fmt.Println("In inline defer") }()

This is allowed in go. Also note that it is mandatory to add “()” after the function otherwise compiler will raise error

expression in defer must be function call

As seen from the output, that the inline function is called after everything in the main is executed and before main returns. That is why

Executed in main

is printed before

In inline Defer
  • 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