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?
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?