Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why is my slice not updating when I append?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading