godefer-keyword

how to defer executing argument in defer function


defer in go schedules a function call to be run after the function completes. So 1st print function fmt.Println("a ", Even()) is defered. But as argument is executed when defer is called, Even() function is called immediately.

package main

import "fmt"

func MakeEvenNumber() func() int {
    num :=0
    return func() (ret int) {
        ret = num
        num = num + 2
        return ret
    }
}

func main() {

    Even := MakeEvenNumber()

    defer fmt.Println("a ", Even())

    fmt.Println("b ", Even())
    fmt.Println("c ", Even())
    fmt.Println("d ", Even())
}

Output:

b  2
c  4
d  6
a  0

This is happened in defer. I just want to know any way to stop executing argument in defer function?

like in this case, output will be:

b 0
c 2
d 4
a 6

defer fmt.Println("a ", **Even()**) this Even() function will be executed along with Println.

Any way to do this?


Solution

  • If you wrap the fmt.Println call in another function (an anonymous function, in this case), the evaluation of Even() will happen after the other calls to Even have completed:

    func main() {
        Even := MakeEvenNumber()
    
        defer func() {
          fmt.Println("a ", Even())
        }()
    
        fmt.Println("b ", Even())
        fmt.Println("c ", Even())
        fmt.Println("d ", Even())
    }