# 7.1. 数组声明和初始化

## 7.1.1 概念

``var identifier [len]type``

``var arr1 [5]int``

arr1 的长度是 5，索引范围从 0 到 `len(arr1)-1`

``runtime error: index out of range``

• 通过 for 初始化数组项
• 通过 for 打印数组元素
• 通过 for 依次处理元素

``````package main
import "fmt"

func main() {
var arr1 [5]int

for i:=0; i < len(arr1); i++ {
arr1[i] = i * 2
}

for i:=0; i < len(arr1); i++ {
fmt.Printf("Array at index %d is %d\n", i, arr1[i])
}
}``````

``````Array at index 0 is 0
Array at index 1 is 2
Array at index 2 is 4
Array at index 3 is 6
Array at index 4 is 8``````

for 循环中的条件非常重要：`i < len(arr1)`，如果写成 `i <= len(arr1)` 的话会产生越界错误。

IDIOM:

``````for i:=0; i < len(arr1); i++｛
arr1[i] = ...
}``````

IDIOM:

``````for i,_:= range arr1 {
...
}``````

``````a := [...]string{"a", "b", "c", "d"}
for i := range a {
fmt.Println("Array item", i, "is", a[i])
}``````

Go 语言中的数组是一种 值类型（不像 C/C++ 中是指向首元素的指针），所以可以通过 `new()` 来创建： `var arr1 = new([5]int)`

``````arr2 := *arr1
arr2[2] = 100``````

``````package main
import "fmt"
func f(a [3]int) { fmt.Println(a) }
func fp(a *[3]int) { fmt.Println(a) }

func main() {
var ar [3]int
f(ar)     // passes a copy of ar
fp(&ar) // passes a pointer to ar
}``````

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

## 7.1.2 数组常量

``````package main
import "fmt"

func main() {
// var arrAge = [5]int{18, 20, 15, 22, 16}
// var arrLazy = [...]int{5, 6, 7, 8, 22}
// var arrLazy = []int{5, 6, 7, 8, 22}
var arrKeyValue = [5]string{3: "Chris", 4: "Ron"}
// var arrKeyValue = []string{3: "Chris", 4: "Ron"}

for i:=0; i < len(arrKeyValue); i++ {
fmt.Printf("Person at %d is %s\n", i, arrKeyValue[i])
}
}``````

``var arrAge = [5]int{18, 20, 15, 22, 16}``

``var arrLazy = [...]int{5, 6, 7, 8, 22}``

`...` 可同样可以忽略，从技术上说它们其实变化成了切片。

``var arrKeyValue = [5]string{3: "Chris", 4: "Ron"}``

``````Person at 0 is
Person at 1 is
Person at 2 is
Person at 3 is Chris
Person at 4 is Ron``````

``````package main
import "fmt"

func fp(a *[3]int) { fmt.Println(a) }

func main() {
for i := 0; i < 3; i++ {
fp(&[3]int{i, i * i, i * i * i})
}
}``````

``````&[0 0 0]
&[1 1 1]
&[2 4 8]``````

``````type Vector3D [3]float32
var vec Vector3D``````

## 7.1.3 多维数组

``````package main
const (
WIDTH  = 1920
HEIGHT = 1080
)

type pixel int
var screen [WIDTH][HEIGHT]pixel

func main() {
for y := 0; y < HEIGHT; y++ {
for x := 0; x < WIDTH; x++ {
screen[x][y] = 0
}
}
}``````

## 7.1.4 将数组传递给函数

• 传递数组的指针
• 使用数组的切片

``````package main
import "fmt"

func main() {
array := [3]float64{7.0, 8.5, 9.1}
x := Sum(&array) // Note the explicit address-of operator
// to pass a pointer to the array
fmt.Printf("The sum of the array is: %f", x)
}

func Sum(a *[3]float64) (sum float64) {
for _, v := range *a { // derefencing *a to get back to the array is not necessary!
sum += v
}
return
}``````

``The sum of the array is: 24.600000``

0 个点赞 | 6 个回复 | 问答
range后面的指针变量可以不解引用使用
0 个点赞 | 4 个回复 | 问答