dpspn60064 2012-09-05 03:37
浏览 85
已采纳

为什么GO中切片的内容未更改?

I thought that in GO language, slices are passed by reference. But why the following code doesn't change the content of slice c? Am I missing something? Thank you.

package main

import (
    "fmt"
)


func call(c []int) {
    c = append(c, 1)
    fmt.Println(c)
}

func main() {
    c := make([]int, 1, 5)
    fmt.Println(c)
    call(c)
    fmt.Println(c)
}

The result printed is:

[0] [0 1] [0]

while I was expecting

[0] [0 1] [0 1]

  • 写回答

2条回答 默认 最新

  • dscbxou1900343 2012-09-05 03:44
    关注

    The length of the slice is kept in the slice header which is not passed by reference. You can think of a slice as a struct containing a pointer to the array, a length, and a capacity.

    When you appended to the slice, you modified index 1 in the data array and then incremented the length in the slice header. When you returned, c in the main function had a length of 1 and so printed the same data.

    The reason slices work this way is so you can have multiple slices pointing to the same data. For example:

    x := []int{1,2,3}
    y := x[:2] // [1 2]
    z := x[1:] // [2 3]
    

    All three of those slices point to overlapping data in the same underlying array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭