doufeng1249 2016-11-22 07:09
浏览 165
已采纳

Golang数组更新不起作用

Hi Golang newbie coming from Java world. I have this very simple piece of program:

package main

import "fmt"

type Foo struct {
  A [5]int
}

func main() {
  s := make([]Foo, 0)
  var foo Foo
  s = append(s, foo)
  foo.A[0] = 42
  fmt.Printf("%v", s[0].A)
}

However, this prints [0,0,0,0,0] instead of [42,0,0,0,0] that I expected. After swapping the line s = append(s, foo) and foo.A[0] = 42, it does print [42,0,0,0,0]. Why is that? Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dqsong2010 2016-11-22 07:21
    关注

    s is a slice with elements of type Foo. Foo is a struct type. Structs, when assigned to a value, passed as an argument, or appended to a slice, are copied by value. Your append line is adding a copy of foo to s, while you intended to add a reference to foo.

    To fix, make s a slice of pointers to your struct:

    s := make([]*Foo)
    var foo Foo
    s = append(s, &foo)
    

    playground link

    Pointers may seem scary to people who have only experienced them painfully in c. In go, they simply allow you to control if you want to copy something or pass a reference to it.

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

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致