douxian7117
douxian7117
2016-10-12 08:15

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dplo59755 dplo59755 5年前

    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

    点赞 评论 复制链接分享

为你推荐