GoLang:如何从2D切片中删除元素?

I've recently been messing around with Go and I wanted to see how it would be to delete an element from a two-dimensional slice.

For deleting an element from a one-dimensional slice, I can successfully use:

data = append(data[:i], data[i+1:]...)

However, with a two-dimensional slice, using:

data = append(data[i][:j], data[i][j+1:]...)

throws the error:

cannot use append(data[i][:j], data[i][j+1:]...) (type []string) as type [][]string in assignment

Would tackling this require a different approach?

Here is one of the possible approaches Go Playground.

b := [][]int{
    []int{1, 2, 3, 4},
    []int{5, 6, 7, 8},
    []int{9, 0, -1, -2},
    []int{-3, -4, -5, -6},
}
print2D(b)
i, j := 2, 2


tmp := append(b[i][:j], b[i][j+1:]...)
c := append(b[:i], tmp)
c = append(c, b[i+1:]...)
print2D(c)

Basically I am extracting the i-th row, remove the element from it append(b[i][:j], b[i][j+1:]...) and then put this row between the rows.

If someone would tell how to append many elements, it would look even nicer.

A 2D slice in Go is nothing more than a slice of slices. So if you want to remove an element from this 2D slice, effectively you still only have to remove an element from a slice (which is an element of another slice).

There is nothing more involved. Only thing you have to look out is that when you remove an element from the row-slice, the result will only be the "new" value of the row (an element) of the "outer" slice, and not the 2D slice itself. So you have to assign the result to an element of the outer slice, to the row whose element you just removed:

// Remove element at the ith row and jth column:
s[i] = append(s[i][:j], s[i][j+1:]...)

Note that this is identical to the simple "removal from slice" if we substitute s[i] with a (not surprisingly, because s[i] denotes the "row-slice" whose jth element we're removing):

a = append(a[:j], a[j+1:]...)

See this complete example:

s := [][]int{
    {0, 1, 2, 3},
    {4, 5, 6, 7},
    {8, 9, 10, 11},
}

fmt.Println(s)

// Delete element s[1][2] (which is 6)
i, j := 1, 2
s[i] = append(s[i][:j], s[i][j+1:]...)

fmt.Println(s)

Output (try it on the Go Playground):

[[0 1 2 3] [4 5 6 7] [8 9 10 11]]
[[0 1 2 3] [4 5 7] [8 9 10 11]]