Skip to content

cmd/compile: generate closure for go/defer builtin calls #19710

Closed
@unixpickle

Description

@unixpickle

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)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions