1.数组的初始化
//使用初始化列表来设置数组元素的值
var array1 [3]int
var array2 = [3]int{1,2}
var array3 = [4]string{"北京","上海","广州","深圳"}
fmt.Println(array1)
fmt.Println(array2)
fmt.Println(array3)
//编译器根据初始值的个数自行推断数组的长度
var array1 [3]int
var array2 = [...]int{1,2}
var array3 = [...]string{"北京","上海","广州","深圳"}
fmt.Println(array1)
fmt.Println(array2)
fmt.Println(array3)
fmt.Printf("%T\n",array2) //[2]int
fmt.Printf("%T\n",array3) //[4]string
//指定索引值的方式来初始化数组
a := [...]int{1:1,3:5}
fmt.Println(a) //[0 1 0 5]
fmt.Printf("%T\n",a) //[4]int
2.数组的遍历
array := []string{"北京","上海","广州","深圳"}
for i := 0; i < len(array); i++ {
fmt.Println(array[i])
}
for index, value := range array {
fmt.Println(index,value)
}
func arraySum(x [3]int) int {
sum :=0
for _, value := range x {
sum = sum + value
}
return sum
}
func main() {
array:=[3]int {1,2,3}
sum := arraySum(array)
fmt.Println(sum)
}
3.多维数组
//二维数组的定义
array := [3][2]int{
{1,2},
{3,4},
{5,6},
}
fmt.Println(array)
fmt.Println(array[1][0])
//二维数组的遍历
array := [3][2]int{
{1,2},
{3,4},
{5,6},
}
for _,v1 := range array {
for _, v2 := range v1 {
fmt.Println(v2)
}
}
//多维数组只有第一层可以使用...来让编译器推导数组长度
array :=[...][2]string{
{"北京","上海"},
{"广州","深圳"},
{"中国台湾","中国香港"},
}
fmt.Println(array)
4.数组是值类型
func modifyArray(x [3]int) {
x[0] = 100
}
func main() {
array :=[3]int{10,20,30}
modifyArray(array) //修改的是副本
fmt.Println(array) //不会改变本身的值
}