Append to slice of slices – golang


I’m trying to implement a golang function to solve the array subset problem. I’m having an issue hard copying a slice of ints to my 2D slice:

// Subsets
func Subsets(nums []int) [][]int {
    // create 2D slice
    sets := make([][]int, 0)
    backtrack(sets, make([]int, 0), nums, 0)
    return sets

func backtrack(sets [][]int, tempList []int, nums []int, start int) {
    // insert current list
    sets = append(sets, tempList)           // <---------HERE
    for i := start; i < len(nums); i++ {
        tempList = append(tempList, nums[i])
        backtrack(sets, tempList, nums, i+1)
        tempList = tempList[:len(tempList)-1]

I tried replace the append statement with:

    buffer := make([]int, len(tempList))
    copy(buffer, tempList)
    sets = append(sets, buffer)

however I still see the sets slices empty when the program ends. An identical copy of this function works just fine in java with the append line as follow:

    list.add(new ArrayList<>(tempList));

what’s the correct way to do this in golang?


I am not sure exactly what is the requirement here. But there are couple of things to note:
Pass by Value : You are passing the sets to backtrack function. When you do that Go copies it’s value and passes it to backtrack function. However, the modified sets is not returned back.
See these changes on the go Play ground.

Answered By – Shakthi Thillai

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.