【问题标题】:Append to array of struct inside a struct追加到结构内的结构数组
【发布时间】:2017-06-10 03:31:38
【问题描述】:
type Customer struct{
    UID string     
    Name string 
    Contact []ContactInfo
}
type ContactInfo struct {
    Number int
}

可以有多个客户,每个客户可以有多个联系电话。 我正在使用以下方法为特定用户附加结构的联系人数组,如下所示。

customer := &Customer{}
customer.UID = args[0]
customer.Name = args[1]
c:= &ContactInfo{}
c.Number = args[2]
customer.Contact= append(customer.Contact, *c)

但这种方法不起作用,因为我只得到最新的联系人,而不是输出中的联系人数组。

【问题讨论】:

  • 您调用append 的方式没有任何问题(尽管没有理由将c 设为指针并在append 中取消引用它)。问题可能在您的代码中的其他地方。我对args 可能是什么类型感到困惑,以便您可以将它的元素分配给string 和int 字段。
  • 你的代码看起来不错。能否请你多分享一点你的代码。分享的部分代码很完美
  • 您的代码看起来不错,也许这就是您输出结构的方式。当我使用您的课程时,我可以看到多个联系信息:play.golang.org/p/RFnqe3n_fu

标签: arrays go struct


【解决方案1】:

当您将对象按值传递给函数或方法时,观察到的行为是可能的。这些函数内部的修改在外部是不可见的。

请看下面的代码

package main

import (
    "fmt"
)

type X struct{
    Y []string
}

func modify(x X) {
    x.Y = append(x.Y, "modify")
}

func (x X) change() {
    x.Y = append(x.Y, "modify")
}

func main() {
    x := X{}
    modify(x)
    x.change()
    fmt.Printf("%+v\n", x)
}

【讨论】:

  • 如果我愿意,我该如何实现?
猜你喜欢
  • 2015-10-01
  • 1970-01-01
  • 2017-05-21
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
相关资源
最近更新 更多