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

报告相同问题?