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?

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

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面