gpt4 book ai didi

arrays - 追加到结构内的结构数组

转载 作者:IT王子 更新时间:2023-10-29 02:22:26 25 4
gpt4 key购买 nike

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)

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

最佳答案

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

看下面的代码

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

关于arrays - 追加到结构内的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41843351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com