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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀