# Go 语言数组

## Go 语言数组

Go 语言提供了数组类型的数据结构。

### 声明数组

Go 语言数组声明需要指定元素类型及元素个数，语法格式如下：

``````var variable_name [SIZE] variable_type
``````

``````var balance [10] float32
``````

### 初始化数组

``````var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
``````

``````balance := [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
``````

``````var balance = [...]float32{1000.0, 2.0, 3.4, 7.0, 50.0}

balance := [...]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
``````

``````//  将索引为 1 和 3 的元素初始化
balance := [5]float32{1:2.0,3:7.0}
``````

`````` balance[4] = 50.0
``````

### 访问数组元素

``````var salary float32 = balance[9]
``````

### 实例 1

``````package main

import "fmt"

func main() {
var n [10]int /* n 是一个长度为 10 的数组 */
var i,j int

/* 为数组 n 初始化元素 */*
for i = 0; i < 10; i++ {
n[i] = i + 100 /* 设置元素为 i + 100 */
}

/* 输出每个数组元素的值 */
for j = 0; j < 10; j++ {
fmt.Printf("Element[%d] = %d**\n**", j, n[j] )
}
}
``````

``````Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
``````

### 实例 2

``````package main

import "fmt"

func main() {
var i,j,k int
// 声明数组的同时快速初始化数组
balance := [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}

/* 输出数组元素 */     ...
for i = 0; i < 5; i++ {
fmt.Printf("balance[%d] = %f\n", i, balance[i] )
}

balance2 := [...]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
/* 输出每个数组元素的值 */
for j = 0; j < 5; j++ {
fmt.Printf("balance2[%d] = %f\n", j, balance2[j] )
}

//  将索引为 1 和 3 的元素初始化
balance3 := [5]float32{1:2.0,3:7.0}
for k = 0; k < 5; k++ {
fmt.Printf("balance3[%d] = %f\n", k, balance3[k] )
}
}
``````

``````balance[0] = 1000.000000
balance[1] = 2.000000
balance[2] = 3.400000
balance[3] = 7.000000
balance[4] = 50.000000
balance2[0] = 1000.000000
balance2[1] = 2.000000
balance2[2] = 3.400000
balance2[3] = 7.000000
balance2[4] = 50.000000
balance3[0] = 0.000000
balance3[1] = 2.000000
balance3[2] = 0.000000
balance3[3] = 7.000000
balance3[4] = 0.000000
``````

Go 语言数组

(0)
(0)