table of Contents
Array go language
Brief introduction
An array is a collection of elements of the same data type, continuous fixed-size space, and a list of such dynamic Python language somewhat different.
The array length has been determined at the time of the statement, or the compiler determines late can modify the array members, but can not modify the size.
definition
format:
var 数组变量名 [元素数量]类型
Declare a variable named team
length of 4, the element type string
of the array:
var team [4]string
note:
Length of the array must be a constant. Type is part of the length of the array, such as var team1 [2]string
and the team
type is not the same.
initialization
Empty array
var kong = []string{}
method 1
Use initialization list to set the value of the array elements:
package main
import (
"fmt"
)
func main() {
// 声明并初始化
var team = [4]string{"Linux", "Python","Java","Go"}
// [Linux Python Java Go]
fmt.Println(team)
}
Method 2
Let the compiler determine the length of the array:
package main
import (
"fmt"
)
func main() {
// 让编译器确定数组的长度
var team = [...]string{"Linux", "Python","Java","Go"}
// [Linux Python Java Go]
fmt.Println(team)
}
Method 3
You can also use the specified index value way to initialize the array:
package main
import (
"fmt"
)
func main() {
// 指定索引值的方式来初始化数
var team = [...]string{1: "Linux", 2: "Python",4: "Java",3: "Go"}
// [Linux Python Java Go]
fmt.Println(team)
}
Array traversal
for range
package main
import (
"fmt"
)
func main() {
var team = [...]string{0: "Linux", 1: "Python",3: "Java",2: "Go"}
// 数组遍历:for range
for index, value := range team {
fmt.Printf("索引:%d\t索引值:%v\n", index, value)
}
}
for
package main
import "fmt"
func main() {
var team = [...]string{0: "Linux", 1: "Python", 3: "Java", 2: "Go"}
for i := 0; i < len(team); i++ {
fmt.Printf("索引:%d\t索引值:%v\n", i, team[i])
}
}
Like two results:
索引:0 索引值:Linux
索引:1 索引值:Python
索引:2 索引值:Go
索引:3 索引值:Java