duanji1043 2019-08-08 18:58
浏览 229
已采纳

Go中的函数返回一个新切片还是指向第一个切片的基础数组的切片?

I'm trying to make my code more performative saving memory if possible

I did some research but couldn't find anything about this specific case.

func createSlice() []int {
    return s[]int{1,2,3}
}

func main() {
    s2 := createSlice()
}

Would s2 be a completely new slice with its own underlying arrays or it would be a slice pointing to the underlying arrays of s?

  • 写回答

1条回答 默认 最新

  • dtwye28880 2019-08-08 19:28
    关注

    You must know about the header of Go Slices. Then, you can have your answer yourself.

    See what's in a slice header by checking out the reflect.SliceHeader type:

    type SliceHeader struct {
        Data uintptr
        Len  int
        Cap  int
    }
    

    Actually, Slice value is a header, containing the backing array along with the length and the capacity. It contains a pointer to the array of the elements are actually stored. The slice value does not contain the elements (unlike arrays).

    So, when a slice is passed or returned, a copy will be passed or returned from this header along with the pointer. This pointer points to the same backed array. So, if you modify the elements of the slice, it modifies the backed array too and so all slices (those share the same backed array) also get the change.

    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.

    See the blog https://blog.golang.org/go-slices-usage-and-internals.

    Ref: Are golang slices passed by value?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?