Skip to content

math/rand: rand package shuffle won't be pass-by-value #51579

Description

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

$ go version
go version go1.17.7 windows/amd64

Does this issue reproduce with the latest release?

yes

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\仮\AppData\Local\go-build
set GOENV=C:\Users\仮\AppData\Roaming\go\env
set GOEXE=.exe
set GOEXPERIMENT=
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=C:\Users\仮\go\pkg\mod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=C:\Users\仮\go
set GOPRIVATE=
set GOPROXY=https://proxy.golang.org,direct
set GOROOT=C:\Program Files\Go
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=C:\Program Files\Go\pkg\tool\windows_amd64
set GOVCS=
set GOVERSION=go1.17.7
set GCCGO=gccgo
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=NUL
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 -mthreads -fmessage-length=0 -fdebug-prefix-map=C:\Users\仮\AppData\Local\Temp\go-build1844132378=/tmp/go-build -gno-record-gcc-switches

What did you do?

doesnt work: https://go.dev/play/p/CXHEZ55IPzg

This works: https://go.dev/play/p/eeODcV4G03t

What did you expect to see?

func main() {
	var list = []string{"1", "2", "3", "4", "5"}

	fmt.Println(shuffleStrings(list)) // [1 5 4 2 3]
	fmt.Println(list) // [1 2 3 4 5]
}
func shuffleStrings(input []string) []string {
	if len(input) == 0 {
		return input
	}

	var copy []string
	for _, v := range input {
		copy = append(copy, v)
	}
	rand.Seed(23443435435423)
	rand.Shuffle(len(copy), func(i, j int) { copy[i], copy[j] = copy[j], copy[i] })
	return copy
}

This is expected behavior

What did you see instead?

func main() {
	var list = []string{"1", "2", "3", "4", "5"}

	fmt.Println(shuffleStrings(list)) // result: [5 3 1 2 4]
	fmt.Println(list) // result: [5 3 1 2 4]
}

func shuffleStrings(input []string) []string {
	rand.Seed(34534543342)
	rand.Shuffle(len(input), func(i, j int) { input[i], input[j] = input[j], input[i] })
	return input
}

Why do shuffleStrings() function change original array
Not pass-by-value

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions