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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
package main
import (
"fmt"
)
func main() {
// 1. 常用初始化
var arrAge = [5]int{15,16,15,18,17} // [5]int{15,16,15,18,17}
// 2. 指定索引位置的初始化
var arrName = [5]string{3:"Chris", 4:"Ron"} // [5]string{"","","","Chris", "Ron"}
var arrCount = [4]int{500, 2:100} // [4]int{500,0,100,0}
// 3. 数组长度初始化根据元素多少决定
var arrLazy = [...]int{5,6,7,8,23} // [5]int{5,6,7,8,23}
var arrPack = [...]int{10,5:100} // [6]int{10,0,0,0,0,100}
// 4. 不指定默认值
var arrRoom [20]int // [20]int{0,0,0,...}
// 5. 使用new函数
var arrBed = new([20]int) // *[20]int{0,0,0,...}
// 6. 数组类型是结构体
d := [...]struct{
name string // 占16字节
age uint8 // 占1字节 内存对齐后 占8字节
}{
{"user1", 10},
{"user2", 20}, // 别忘了最后一行的逗号,这是由于GO语法解析
}
fmt.Println(unsafe.Sizeof(d)) // 48 = (16+8) * 2
fmt.Printf("arrAge:%#v arrAge:Type:%T\n", arrAge, arrAge)
fmt.Printf("arrName:%#v arrName:Type:%T\n", arrName, arrName)
fmt.Printf("arrCount:%#v arrCount:Type:%T\n", arrCount, arrCount)
fmt.Printf("arrLazy:%#v arrLazy:Type:%T\n", arrLazy, arrLazy)
fmt.Printf("arrPack:%#v arrPack:Type:%T\n", arrPack, arrPack)
fmt.Printf("arrRoom:%#v arrRoom:Type:%T\n", arrRoom, arrRoom)
fmt.Printf("arrBed:%#v arrBed:Type:%T\n", arrBed, arrBed)
fmt.Printf("d:%#v d:Type:%T\n", d, d)
}
/*
* arrAge:[5]int{15, 16, 15, 18, 17} arrAge:Type:[5]int
* arrName:[5]string{"", "", "", "Chris", "Ron"} arrName:Type:[5]string
* arrCount:[4]int{500, 0, 100, 0} arrCount:Type:[4]int
* arrLazy:[5]int{5, 6, 7, 8, 23} arrLazy:Type:[5]int
* arrPack:[6]int{10, 0, 0, 0, 0, 100} arrPack:Type:[6]int
* arrRoom:[20]int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} arrRoom:Type:[20]int
* arrBed:&[20]int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} arrBed:Type:*[20]int
* d:
* [2]struct { name string; age uint8 }
* {
* struct { name string; age uint8 }{name:"user1", age:0xa},
* struct { name string; age uint8 }{name:"user2", age:0x14}
* }
* d:Type:
* [2]struct { name string; age uint8 }
*/
|