Golang切片是否按值传递?

问题描述:

In Golang, I am trying to make a scramble slice function for my traveling salesman problem. While doing this I noticed when I started editing the slice I gave the scramble function was different every time I passed it in.

After some debugging I found out it was due to me editing the slice inside the function. But since Golang is supposed to be a "pass by value" language, how is this possible?

https://play.golang.org/p/mMivoH0TuV

I have provided a playground link to show what I mean. By removing line 27 you get a different output than leaving it in, this should not make a difference since the function is supposed to make its own copy of the slice when passed in as an argument.
Can someone explain the phenomenon?

在Golang中,我试图为我的旅行推销员问题创建一个加扰切片函数。 这样做时,我注意到当我开始编辑切片时,每次传入时,我赋予的加密功能都是不同的。 p>

经过一些调试后,我发现这是由于我编辑了切片 在函数内部。 但是既然Golang被认为是一种“价值传递”的语言,那怎么可能呢? p>

https://play.golang.org/p/mMivoH0TuV p>

我提供了一个游乐场链接来显示我的意思。 通过删除第27行,您得到的输出不同于保留的输出,这应该不会有所区别,因为该功能
有人可以解释这种现象吗? p> div>

Yes, everything in Go is passed by value. Slices too. But a slice value is a header, describing a contiguous section of a backing array, and a slice value only contains a pointer to the array where the elements are actually stored. The slice value does not include its elements (unlike arrays).

So when you pass a slice to a function, a copy will be made from this header, including the pointer, which will point to the same backing array. Modifying the elements of the slice implies modifying the elements of the backing array, and so all slices which share the same backing array will "observe" the change.

To see what's in a slice header, check out the reflect.SliceHeader type:

type SliceHeader struct {
    Data uintptr
    Len  int
    Cap  int
}

See related / possible duplicate question: Are Golang function parameter passed as copy-on-write?

Read blog post: Go Slices: usage and internals