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

Appending anonymous function pointer to slice overwrites previous pointers #43565

Closed
soypat opened this issue Jan 7, 2021 · 1 comment
Closed

Comments

@soypat
Copy link

soypat commented Jan 7, 2021

What version of Go are you using (go version)?

$ go version
go version go1.15.6 windows/amd64

Does this issue reproduce with the latest release?

15.6 is latest release I believe.

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
set GO111MODULE=
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users\grade\AppData\Local\go-build
set GOENV=C:\Users\grade\AppData\Roaming\go\env
set GOEXE=.exe
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=C:\Users\grade\go\pkg\mod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=C:\Users\grade\go
set GOPRIVATE=
set GOPROXY=https://proxy.golang.org,direct
set GOROOT=c:\go
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=c:\go\pkg\tool\windows_amd64
set GCCGO=gccgo
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=0
set GOMOD=C:\Users\grade\Documents\src\godesim\go.mod
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=C:\Users\grade\AppData\Local\Temp\go-build485996670=/tmp/go-build -gno-record-gcc-switches

What did you do?

MWE: https://play.golang.org/p/aV6OpQwtc4K

package main

import (
	"fmt"
)

func main() {
	var x  = []func(){
		func() { fmt.Println("First printer") },
		func() { fmt.Println("Second printer") },
		func() { fmt.Println("Third printer") },
	}
	
	var y = make([]*func(),0)
	for _, v := range x {
		y = append(y, &v) // append pointers to slice
	}
	for _, v := range y {
		(*v)()
	}
}

Full example with comments on why this is counterintuitive:
https://play.golang.org/p/aFDUcEGu2zV

What did you expect to see?

First Printer
Second Printer
Third Printer

What did you see instead?

Third printer
Third printer
Third printer
@soypat soypat closed this as completed Jan 7, 2021
@soypat
Copy link
Author

soypat commented Jan 7, 2021

v's value is changed on every iteration and since I'm passing a pointer, so are they

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

2 participants