douchun1900 2018-05-15 12:38
浏览 65
已采纳

将数组作为函数参数传递

I expected the following code snippet either to produce a as {0x01, 0x02} (pass by value) or as {0x03, 0x02, 0x01} (pass by reference). Strangely, it produces the output as {0x03, 0x02}. Could you please help me understand why is that?

package main

import "fmt"

func test1(t []byte) {
    t[0] = 0x03
    t = append(t, 0x01 )
}

func main() {
    a := []byte{0x01, 0x02 }
    test1(a)
    _ = a
    fmt.Printf("%v", a)
}
  • 写回答

2条回答 默认 最新

  • douyi0902 2018-05-15 12:49
    关注

    In Go []byte is not an array, it's a byte slice.

    What happened is that the size of a was 2, and because of that, after its first element was changed to 3, append allocated a new bigger slice - and t was set to the address of the new slice that was allocated, but that doesn't affect the a in main.

    From A Tour of Go about append:

    If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大