# Golang二维切片初始化

Dreamcats · · 132 次点击 · · 开始浏览

# Golang二维切片初始化

## 引言

``````var a = [5]int{1, 2, 3, 4, 5} // 用var
b := [5]int{1, 2, 3, 4, 5} // 用类型推断
var c = [...]int{1, 2, 3, 4, 5} // 不确定长度
d := [...]int{1, 2, 3, 4, 5}
``````

``````var a [5]int
b := [5]int{}
c := make([]int, 5)
``````

## 二维数组初始化

``````var a [3][4]int
``````

``````[[0 0 0 0] [0 0 0 0] [0 0 0 0]]
``````

``````a := [3][4]int{}
``````

``````[[0 0 0 0] [0 0 0 0] [0 0 0 0]]
``````

``````m, n := 3, 4
var a [m][n]int // 报错，必须是常量表达式
``````

``````func main() {
m, n := 3, 4
a := make([][]int, m) // 二维切片，3行
for i := range a {
a[i] = make([]int, n) // 每一行4列
}
fmt.Println(a)
}
``````

``````[[0 0 0 0] [0 0 0 0] [0 0 0 0]]
``````

``````var a []int // or a := []int{}
fmt.Println(a) // []
a[0] = 1 // 报错
``````

## 总结

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

# Golang二维切片初始化

## 引言

``````var a = [5]int{1, 2, 3, 4, 5} // 用var
b := [5]int{1, 2, 3, 4, 5} // 用类型推断
var c = [...]int{1, 2, 3, 4, 5} // 不确定长度
d := [...]int{1, 2, 3, 4, 5}
``````

``````var a [5]int
b := [5]int{}
c := make([]int, 5)
``````

## 二维数组初始化

``````var a [3][4]int
``````

``````[[0 0 0 0] [0 0 0 0] [0 0 0 0]]
``````

``````a := [3][4]int{}
``````

``````[[0 0 0 0] [0 0 0 0] [0 0 0 0]]
``````

``````m, n := 3, 4
var a [m][n]int // 报错，必须是常量表达式
``````

``````func main() {
m, n := 3, 4
a := make([][]int, m) // 二维切片，3行
for i := range a {
a[i] = make([]int, n) // 每一行4列
}
fmt.Println(a)
}
``````

``````[[0 0 0 0] [0 0 0 0] [0 0 0 0]]
``````

``````var a []int // or a := []int{}
fmt.Println(a) // []
a[0] = 1 // 报错
``````