Original post

ansMap := map[[3]int]bool{}
// after some operations, I need the keys appending to ans
ans := [][]int{}
// so I do this
for pair := range ansMap {
        ans = append(ans, pair[:])  // now ans is filled with the same slice
}

I am pretty new to go, I read when appending a slice, it is the pointer that gets passed, so when pair gets new value from ansMap, the old pair that has already been appended to ans also gets updated, I end up with ans filling with the same slice.

How can I get around this?

Hi, @W-Qiu,

Slicing an array keeps reusing that array. You need to copy the elements into separate slices:

for pair := range ansMap {
    dup := make([]int, len(pair))
    copy(dup, pair[:])
    ans = append(ans, dup)
}

A more efficient way to store this would be in a single backing slice:

// note that the capacity has to be set or this will end up worse than just having separate slices:
allPairs := make([]int, 0, len(ansMap)*3)
for pair := range ansMap {
    allPairs = append(allPairs, pair[:]...)
    ans = append(ans, allPairs[len(allPairs)-3:])
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.