Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between named return value and normal return value?

Tags:

go

My question is about the different named return value vs normal return value.

my code

package main

import "fmt"

func main() {
    f := fmt.Println
    f(a())
    f(b())
}

func a() int {
    i := 0
    defer func() {
        i += 1
        fmt.Println("a defer : ", i)
    }()

    return i
}

func b() (i int) {
    i = 0

    defer func() {
        i += 1
        fmt.Println("b defer : ", i)
    }()
    return i
}

the result:

the a function return 0

the b function reutrn 1

Why?

like image 670
Blue Joy Avatar asked Feb 08 '18 07:02

Blue Joy


1 Answers

The named return value also allocates a variable for the scope of your function.

func a() int: While you already return the value of i = 0, but since no named values was defined the static value got returned. So even though you're increasing i in the deferred function it doesn't affect the returned value.

func b() (i int): The variable i is allocated (and already initialized to 0). Even though the deferred function runs after the i = 0 was returned the scope is still accessible and thus still can be changed.


Another point of view: you can still change named return values in deferred functions, but cannot change regular return values.

This especially holds true in the following example:

func c() (i int) {
    defer func() {
        i = 1
        fmt.Println("c defer : ", i)
    }()
    return 0
}
like image 178
Kevin Sandow Avatar answered Sep 21 '22 23:09

Kevin Sandow