Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Behavior of deferred functions in go

I am calling the following function

func main() {
    defer func(t time.Time) {
        log.Printf("took=%v", time.Since(t))
    }(time.Now())
    time.Sleep(5 * time.Second)
}

I noticed that as expected, the deferred function reports the actual entire time of execution.

â–¶ go run main.go
2022/01/08 15:20:03 took=5.005078652s

My question is what is the actual mechanism that allows this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does this line defer func(t time.Time) imply that at this specific point the invocation is actually done (therefore t takes the temporal value at this point in time) and that is the way it can estimate the actual (main) function invocation?

Otherwise, it the deferred anonymous function was entirely invoked just before main‘s exist, how would it know when main actually begun execution?

>Solution :

Yes, this is what even Go tour says:

The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading