Closed
Description
Please answer these questions before submitting your issue. Thanks!
What version of Go are you using (go version
)?
Go 1.8.
Also happens on play.golang.org.
What operating system and processor architecture are you using (go env
)?
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
What did you do?
Evaluate this code:
package main
import "fmt"
func main() {
fmt.Println("should be 0:", len(foobar()))
}
func foobar() map[int]bool {
m := map[int]bool{}
for i := 0; i < 3; i++ {
m[i] = true
defer delete(m, i)
}
return m
}
What did you expect to see?
should be 0: 0
What did you see instead?
should be 0: 2
The defer
statement is supposed to freeze its arguments the instant it is evaluated, but it does not when used with delete
. Compare to this program, which works correctly:
package main
import "fmt"
func main() {
fmt.Println("should be 0:", len(foobar()))
}
func foobar() map[int]bool {
m := map[int]bool{}
for i := 0; i < 3; i++ {
m[i] = true
defer myDelete(m, i)
}
return m
}
func myDelete(m map[int]bool, k int) {
delete(m, k)
}