Welcome To Golang By Example

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

Defer function and Named Return Values in Go (Golang)

Posted on September 22, 2020September 22, 2020 by admin

Table of Contents

  • Overview
  • Example

Overview

In case of named return value in the function, the defer function can read as well as modified those named return values. If the defer function modifies the name return value then that modified value will  be returned

Let’s see a program for that

Example

package main
import "fmt"
func main() {
    s := test()
    fmt.Println(s)
}
func test() (size int) {
    defer func() { size = 20 }()
    size = 30
    return
}

Output

20

In the above program we have named return value “size”  in the the test function. In the defer function we modify the name return value and we change the value to 20.  We then set size to 30. In the main function we print the return value of test function  and it outputs 20 instead of 30 because defer function has modified the value of size variable in the test function

  • 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