1.数组的初始化

  1. //使用初始化列表来设置数组元素的值
  2. var array1 [3]int
  3. var array2 = [3]int{1,2}
  4. var array3 = [4]string{"北京","上海","广州","深圳"}
  5. fmt.Println(array1)
  6. fmt.Println(array2)
  7. fmt.Println(array3)
  1. //编译器根据初始值的个数自行推断数组的长度
  2. var array1 [3]int
  3. var array2 = [...]int{1,2}
  4. var array3 = [...]string{"北京","上海","广州","深圳"}
  5. fmt.Println(array1)
  6. fmt.Println(array2)
  7. fmt.Println(array3)
  8. fmt.Printf("%T\n",array2) //[2]int
  9. fmt.Printf("%T\n",array3) //[4]string
  1. //指定索引值的方式来初始化数组
  2. a := [...]int{1:1,3:5}
  3. fmt.Println(a) //[0 1 0 5]
  4. fmt.Printf("%T\n",a) //[4]int

2.数组的遍历

  1. array := []string{"北京","上海","广州","深圳"}
  2. for i := 0; i < len(array); i++ {
  3. fmt.Println(array[i])
  4. }
  5. for index, value := range array {
  6. fmt.Println(index,value)
  7. }
  1. func arraySum(x [3]int) int {
  2. sum :=0
  3. for _, value := range x {
  4. sum = sum + value
  5. }
  6. return sum
  7. }
  8. func main() {
  9. array:=[3]int {1,2,3}
  10. sum := arraySum(array)
  11. fmt.Println(sum)
  12. }

3.多维数组

  1. //二维数组的定义
  2. array := [3][2]int{
  3. {1,2},
  4. {3,4},
  5. {5,6},
  6. }
  7. fmt.Println(array)
  8. fmt.Println(array[1][0])
  1. //二维数组的遍历
  2. array := [3][2]int{
  3. {1,2},
  4. {3,4},
  5. {5,6},
  6. }
  7. for _,v1 := range array {
  8. for _, v2 := range v1 {
  9. fmt.Println(v2)
  10. }
  11. }
  1. //多维数组只有第一层可以使用...来让编译器推导数组长度
  2. array :=[...][2]string{
  3. {"北京","上海"},
  4. {"广州","深圳"},
  5. {"中国台湾","中国香港"},
  6. }
  7. fmt.Println(array)

4.数组是值类型

  1. func modifyArray(x [3]int) {
  2. x[0] = 100
  3. }
  4. func main() {
  5. array :=[3]int{10,20,30}
  6. modifyArray(array) //修改的是副本
  7. fmt.Println(array) //不会改变本身的值
  8. }