-2

I am trying to add stuff to my slice but somehow the slice is never updated.

endpointsList := make([]string, 3)

for _, route := range routes {
    if len(route.Endpoints) > 0 {
        waitGroup.Add(1)
        go endpointRoutine(route, template, route.Protected, &waitGroup, &endpointsList)
    }
}

I pass the endpointsList by reference, meaning I should be able to assign new things to its memory location I think.

In the function endpointRoutine I do this:

list := make([]string, 3)

for _, r := range route.Endpoints {
    list = append(list, "some data comes here...")
}

endpointsList = &list

When I do a printr after this (below my first bit of code and AFTER the waitGroup.Wait() part) the slice is still empty.

Obviously, I am overwriting the slice now and my final goal is to ADD to the slice. But when I try to add with this code:

endpointsList = append(endpointsList, "fdssdfsdfsdf")

It gives me the error:

cannot use endpointsList (type *[]string) as []Type

Can someone please explain to me what might be wrong?

1 Answers1

1

With endpointsList = &list, you are assigning the pointer pointing to the slice to some other slice. To set the slice, do this instead:

*endpointsList=list
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • Good one, I didnt even notice that mistake, thanks so much :) this got me a bit further towards my goal! anyways, I am overwriting the slice now and I want to add (doh)... endpointsList = append(endpointsList, "fdssdfsdfsdf") this results in an error... any idea? –  Sep 28 '20 at 16:37
  • Had to use (obviously) *endpointsList=list and now it is working succesfully! thanks a lot! –  Sep 28 '20 at 16:59
  • @Ometecuthli while this solves the surface problem, concurrent updates of slices without synchronizing updates [is a bad idea](https://medium.com/@cep21/gos-append-is-not-always-thread-safe-a3034db7975). – colm.anseo Sep 28 '20 at 17:56