go

defer with current value


I would like to call the function using defer with the most current values of parameters in the function's arguments. I suspected that running this code:

package main

import (
    "fmt"
)

func main() {
    s := "ABC"
    
    defer fmt.Println(s)
    s = "DEF"
}

I want to get DEF. But that what I get is ABC. Is there any way to get DEF?


Solution

  • Create a closure around the variable you want to capture:

    https://play.golang.org/p/W4xt_KSOJNj

    s := "ABC"
    
    defer func() {
        fmt.Println(s)
    }()
    s = "DEF"