My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Golang defer function receive params

Default profile photo
Anonymous
·Apr 16, 2019

Here is a golang question about defer function receiving input params. In defer function body, sometimes input param value has received by function, But sometime is not.

why a is 1, b is 0, c is 1?

Thanks.

# go version
go version go1.12 darwin/amd64
package main

import "fmt"

func main() {
    var a int
    defer func(int) {
        fmt.Println("a=", a) //1
    }(a)
    a = 1

    var b int
    defer func(b int) {
        fmt.Println("b=", b) // 0
    }(b)
    b = 1

    var c int
    defer func(c *int) {
        fmt.Println("c=", *c) //1
    }(&c)
    c = 1
}

results is

c= 1
b= 0
a= 1