I’m trying to append a slice in a struct but it simply won’t update. I understand that go is mostly pass by value, but aren’t slices already pointers to an underlying array?
I’ve even tried passing the values through my change function(which uses pointers?) But yet I still get the same result.
package main
import "fmt"
type BookingInfoNode struct {
Car string
Date string
BookingTime int
}
type user struct {
Username string
UserBookings []*BookingInfoNode
}
var mapUsers = make(map[string]user)
func init() {
mapUsers["john"] = user{"john", []*BookingInfoNode{}}
}
func change(a []*BookingInfoNode, booking *BookingInfoNode) []*BookingInfoNode {
a = append(a, booking)
return a
}
func main() {
newBooking := &BookingInfoNode{"mazda", "03/06/2022", 0600}
myUser := mapUsers["john"]
myUser.UserBookings = change(myUser.UserBookings, newBooking)
fmt.Println(myUser.UserBookings)
fmt.Println(mapUsers["john"].UserBookings)
}
With my two printlns I’m expecting:
[memory address]
[memory address]
But I’m getting:
[memory address]
[]
>Solution :
Your append call is working. You forgot to update the map with the appended value though.
The map map[string]user has user struct as its value, thus myUser:=mapUsers["john"] assigns a copy of the user in the map to myUser. The you go on to append to the slice in myUser, but the copy in the map is never updated.
Either change the map to map[string]*user, or write the value back to the map after you change it: mapUsers["john"]=myUser