golang切片是否按照价值传递? [英] Are golang slices pass by value?

查看:124
本文介绍了golang切片是否按照价值传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Golang中,我试图为我的旅行推销员问题制作一个争夺片功能。当我这样做的时候,我注意到当我开始编辑切片时,我每次传递它时都会有所不同。



经过一些调试后,我发现这是由于我编辑函数内的切片。但是因为Golang应该是一种按价值传递的语言,这怎么可能?



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



我提供了一个游乐场链接来展示我的意思。
通过删除第27行,您将得到与输入不同的输出,这应该没有什么区别,因为该函数应该在作为参数传入时自己创建片的副本。

有人可以解释这种现象吗?

解决方案

是的,Go中的所有内容都是按值传递的。切片也是。但是切片值是一个,描述了一个支持数组的连续部分,而切片值只包含一个指向实际存储元素的数组的指针。切片值不包括其元素(与数组不同)($ {

)所以当你将一个切片传递给一个函数时,将从这个头文件创建一个副本,包括指针,它将指向相同的支持数组。修改切片的元素意味着修改后备数组的元素,因此所有共享相同后备数组的切片都将观察该变化。



要查看什么是在切片标题中,查看 reflect.SliceHeader 类型:

  type SliceHeader struct {
Data uintptr
Len int
Cap int

请参阅相关/可能的重复问题:
Golang函数参数是否作为copy-on-write传递?



阅读博客文章: Go切片:用法和内部元素


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?

解决方案

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

这篇关于golang切片是否按照价值传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆