★二维数组的使用方式:
先声明或者定义,再赋值
1)语法:var 数组名[大小][大小]类型
2)比如:var arr[2][3]int[][]
两行三列的二维数组
★二维数组的遍历
1)双层for循环
2)for-range方式完成遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
package main
import (
"fmt"
)
func main() {
//演示二维数组的遍历
var arr3 = [2][3]int{{1,2,3},{4,5,6}}
//for循环来遍历
for i :=0;i < len(arr3);i++{
for j:=0;j < len(arr3[i]);j++{
fmt.Printf("%v\t",arr3[i][j])
}
fmt.Println()
}
//for-range来遍历二维数组
for i,v :=range arr3{
for j,v2 :=range v{
fmt.Printf("arr3[%v][%v]=%v \t",i,j,v2)
}
fmt.Println()
}
}
|
PS:go语言基础之二维数组
1、二维数组
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
package main //必须有个main包
import "fmt"
func main() {
//有多少个[]就是多少维
//有多少个[]就用多少个循环
var a [3][4]int
k := 0
for i := 0; i < 3; i++ {
for j := 0; j < 4; j++ {
k++
a[i][j] = k
fmt.Printf("a[%d][%d] = %d, ", i, j, a[i][j])
}
fmt.Printf("\n")
}
fmt.Println("a = ", a)
//有3个元素,每个元素又是一维数组[4]int
b := [3][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}
fmt.Println("b = ", b)
//部分初始化,没有初始化的值为0
c := [3][4]int{{1, 2, 3}, {5, 6, 7, 8}, {9, 10}}
fmt.Println("c = ", c)
d := [3][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
fmt.Println("d = ", d)
e := [3][4]int{1: {5, 6, 7, 8}}
fmt.Println("e = ", e)
}
|
执行结果:
a[0][0] = 1, a[0][1] = 2, a[0][2] = 3, a[0][3] = 4,
a[1][0] = 5, a[1][1] = 6, a[1][2] = 7, a[1][3] = 8,
a[2][0] = 9, a[2][1] = 10, a[2][2] = 11, a[2][3] = 12,
a = [[1 2 3 4] [5 6 7 8] [9 10 11 12]]
b = [[1 2 3 4] [5 6 7 8] [9 10 11 12]]
c = [[1 2 3 0] [5 6 7 8] [9 10 0 0]]
d = [[1 2 3 4] [5 6 7 8] [0 0 0 0]]
e = [[0 0 0 0] [5 6 7 8] [0 0 0 0]]
以上就是Golang二维数组的使用方式的详细内容,更多关于Golang二维数组的资料请关注服务器之家其它相关文章!
原文链接:https://www.cnblogs.com/ckfuture/p/14820614.html