浅析Go语言中数组的这些细节

len&cap

```package main
​
func main() {
a := [2]int{}
println(len(a), cap(a))
}```

二维数组的遍历

```package main
import (
"fmt"
)
func main() {
var f [2][3]int = [...][3]int{{1, 2, 3}, {7, 8, 9}}
for k1, v1 := range f {
for k2, v2 := range v1 {
fmt.Printf("(%d,%d)=%d ", k1, k2, v2)
}
fmt.Println()
}
}```

数组的拷贝与传参

```package main
import "fmt"
func printArr(arr *[5]int) {
arr[0] = 10
for i, v := range arr {
fmt.Println(i, v)
}
}
func main() {
var arr1 [5]int
printArr(&arr1)
fmt.Println(arr1)
arr2 := [...]int{2, 4, 6, 8, 10}
printArr(&arr2)
fmt.Println(arr2)
}```

求数组所有元素之和

```package main
import (
"fmt"
"math/rand"
"time"
)
func sumArr(a [10]int) int {
var sum int = 0
for i := 0; i < len(a); i++ {
sum += a[i]
}
return sum
}
func main() {
rand.Seed(time.Now().Unix())
var b [10]int
for i := 0; i < len(b); i++ {
b[i] = rand.Intn(1000)
}
sum := sumArr(b)
fmt.Printf("sum=%d\n", sum)
}```

例题：数组元素匹配问题

```package main
import "fmt"
func myTest(a [5]int, target int) {
// 遍历数组
for i := 0; i < len(a); i++ {
other := target - a[i]
// 继续遍历
for j := i + 1; j < len(a); j++ {
if a[j] == other {
fmt.Printf("(%d,%d)\n", i, j)
}
}
}
}
func main() {
b := [5]int{1, 3, 5, 8, 7}
myTest(b, 8)
}```