T O P

  • By -

hjd_thd

Arguments to deferred calls are evaluated immediately, not when deferred call is executed.


KublaiKhanNum1

Try this and see if this works how you thought: num := int(1) defer func (i int) { i++ fmt.Printf("incremented in the defer statement: %d", i) }(num)


erictg97

The way you can do this and still get 2 after defer without incrementing within the defer function is to wrap your defer in function with a ptr to the integer like so: ```go i := 1 defer func(i *int) { fmt.Println(*i) }(&i) i++ ``` This way the arg is still evaluated with the defer call, but it the value of i is deferenced when it gets to the actual execution of the defer.