Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: cmd/vet: references implicitly created from loop variables being passed to go/defer #58887

Closed
Miigon opened this issue Mar 6, 2023 · 2 comments

Comments

@Miigon
Copy link

Miigon commented Mar 6, 2023

Consider the following case:

type MyInt int

func (mi *MyInt) Show() {
	fmt.Println(*mi)
}

func main() {
	ms := []MyInt{50, 60, 70, 80, 90}
	for _, m := range ms {
		go m.Show() // go (&m).Show()
	}

	time.Sleep(100 * time.Millisecond)
}

Result:

90
90
90
90
90

Show() has a pointer type receiver, and loop variable m is of type MyInt. In m.Show(), m will be implicitly converted to a pointer ((&m).Show()), thus implicitly creating a reference to the loop variable that are then passed to go/defer function.

This mistake is more subtle than accidentally capturing loop variables with function literals since it's impossible to detect if only looking at the for loop without also checking the receiver type of Show(). So I think this is worth vetting for.

I imagine a implementation of such check would look a lot like loopclosure. And would share a lot of the same logics (such as maybe? the recent #57173). But it isn't technically caused by "closure" so I'm not sure that's the right place to do it.

@Miigon Miigon added the Proposal label Mar 6, 2023
@gopherbot gopherbot added this to the Proposal milestone Mar 6, 2023
@Miigon Miigon changed the title proposal: cmd/vet: references implicitly converted from values being passed to go/defer proposal: cmd/vet: references implicitly created from loop variables being passed to go/defer Mar 6, 2023
@gophun
Copy link

gophun commented Mar 6, 2023

This is covered by #56010

@ianlancetaylor
Copy link
Contributor

Closing for now, we can reopen if #56010 is declined. Thanks.

@ianlancetaylor ianlancetaylor closed this as not planned Won't fix, can't repro, duplicate, stale Mar 6, 2023
@golang golang locked and limited conversation to collaborators Mar 5, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants