Welcome To Golang By Example

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

Evaluation of defer arguments in Go (Golang)

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

Table of Contents

  • Overview
  • Example
  • Output

Overview

defer arguments are evaluated at the time defer statement is evaluated

Let’s see a program for that

Example

package main

import "fmt"

func main() {
	sample := "abc"

	defer fmt.Printf("In defer sample is: %s\n", sample)
	sample = "xyz"
}

Output

In defer sample is: abc

In the above program when the defer statement was evaluated the value of the sample variable was “abc”. In the defer function, we print the  sample variable. After the defer statement we change the value of the sample variable to “xyz”.  But the program outputs “abc” instead of “xyz” because when the defer arguments were evaluated the value of the  sample variable was “abc”.

  • 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