The strange behavior of defer

127 views
Skip to first unread message

duan...@google.com

unread,
May 20, 2019, 7:54:12 PM5/20/19
to golang-nuts
For the following piece of code.

func main() {
start := time.Now()
defer fmt.Println(time.Since(start))
time.Sleep(1000000000)
fmt.Println("Hello, playground")
fmt.Println(time.Since(start))
}

The output is:

Hello, playground
1s
0s

I'm new at golang. Should the two time.Since both be called after the sleep? 
Thank you!

Kurtis Rader

unread,
May 20, 2019, 8:18:04 PM5/20/19
to duan...@google.com, golang-nuts
Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked.

To keep that from happening you need to use a lambda (or function literal): https://play.golang.org/p/9Avbf_Mwx4g

--
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank

Dan Kortschak

unread,
May 20, 2019, 8:18:10 PM5/20/19
to duan...@google.com, golang-nuts
The parameter to fmt.Println is evaluated at the time of the defer
statement's execution. You should do something like this instead

func main() {
start := time.Now()
defer func() { fmt.Println(time.Since(start)) }()
time.Sleep(1000000000)
fmt.Println("Hello, playground")
fmt.Println(time.Since(start))
}

https://play.golang.org/p/30IQaP3jg5_w

Kebo Duan

unread,
May 20, 2019, 8:21:55 PM5/20/19
to golang-nuts
I see, thank you very much!
Reply all
Reply to author
Forward
0 new messages