简体   繁体   中英

Append to array of struct inside a struct

type Customer struct{
    UID string     
    Name string 
    Contact []ContactInfo
}
type ContactInfo struct {
    Number int
}

There can be multiple customers and each customer can have multiple contact numbers. I was using the following approach to append the Contact array of struct for a particular user as follows.

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

But this approach isn't working as I only get the latest Contact and not the array of Contact in output.

The observed behaviour is possible when you are passing object by value into a function or method. The modifications inside those functions will not be visible outside.

See the code below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM