所以我有这个2D切片,例如:
s := [][]int{
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11},
}
fmt.Println(s)
//Outputs: [[0 1 2 3] [4 5 6 7] [8 9 10 11]]
如何从此2D切片中删除整行,以便在我决定删除中间行时结果如下所示:
[[0 1 2 3] [8 9 10 11]]
非常感谢!
答案 0 :(得分:2)
您可以尝试以下操作:
i := 1
s = append(s[:i],s[i+1:]...)
您可以尝试Golang playground
中的工作代码另一种替代方法是使用以下内容:
i := 1
s = s[:i+copy(s[i:], s[i+1:])]
答案 1 :(得分:2)
删除索引i
处的行的公式为:
s = append(s[:i], s[i+1:])
这是一个有效的例子:
package main
import (
"fmt"
)
func main() {
s := [][]int{
{0, 1, 2, 3},
{4, 5, 6, 7}, // This will be removed.
{8, 9, 10, 11},
}
// Delete row at index 1 without modifying original slice by
// appending to a new slice.
s2 := append([][]int{}, append(s[:1], s[2:]...)...)
fmt.Println(s2)
// Delete row at index 1. Original slice is modified.
s = append(s[:1], s[2:]...)
fmt.Println(s)
}
我建议你阅读Go Slice Tricks。一些技巧也可以应用于多维切片。