go 二维切片初始方法
func main() {
// 方法1
row, col := 4, 5
var res [][]int
for i := 0; i < row; i++ {
inline := make([]int, col)
res = append(answer, inline)
}
fmt.Println(res)
// 方法2
res1 := make([][]int, row)
for i := range res1 {
res1[i] = make([]int, col)
}
fmt.Println(answer1)
}
// [[0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]]
// [[0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]]
当初始长度都是0的时候
func main() {
row, col := 0, 0
res1 := make([][]int, row)
for i := range res1 {
res1[i] = make([]int, col)
}
a := []int{1, 2, 4}
res1 = append(res1, a)
res1 = append(res1, a)
fmt.Println(res1)
//[[1 2 4] [1 2 4]]
}
版权声明:本文为weixin_51299478原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。