Array initialization in Golang

package main
import (
     "fmt"
)
//Note: When the length of the array is less than the capacity, it will be filled automatically
func main() {
     //method one
     var iArr[5]int = [5]int{1, 2, 3, 4}
     fmt.Println(iArr) //[1 2 3 4 0]
     var sArr[3]string = [3]string{"a"}
     fmt.Println(sArr) //[a]
     // method two
     bArr := [3]byte{'a', 'b', 'c'}
     fmt.Println(bArr)
     // way three
     // Determine the length by initialization
     fArr := [...]float64{1.1, 2.2}
     fmt.Println(fArr)
}
func main() {
var testArray[3]int //The array will be initialized to zero value of type int
var numArray = [3]int{1, 2} //initialize with the specified initial value
var cityArray = [3]string{"Beijing", "Shanghai", "Shenzhen"} //Use the specified initial value to complete the initialization
fmt.Println(testArray) //[0 0 0]
fmt.Println(numArray) //[1 2 0]
fmt.Println(cityArray) //[Beijing Shanghai Shenzhen]
}
func main() {
var testArray[3]int
var numArray = [...]int{1, 2}
var cityArray = [...]string{"Beijing", "Shanghai", "Shenzhen"}
fmt.Println(testArray) //[0 0 0]
fmt.Println(numArray) //[1 2]
fmt.Printf("type of numArray:%T\n", numArray) //type of numArray:[2]int
fmt.Println(cityArray) //[Beijing Shanghai Shenzhen]
fmt.Printf("type of cityArray:%T\n", cityArray) //type of cityArray:[3]string
func main() {
	a := [...]int{1: 1, 3: 5}
	fmt.Println(a)                  // [0 1 0 5]
	fmt.Printf("type of a:%T\n", a) //type of a:[4]int
}

traversing the array

func main() {
var a = [...]string{"Beijing", "Shanghai", "Shenzhen"}
// Method 1: for loop traversal
for i := 0; i < len(a); i++ {
fmt.Println(a[i])
}
 
// Method 2: for range traversal
for index, value := range a {
fmt.Println(index, value)
}
}
//////////////////////////////////////////////////////////////////////////////
func main() {
a := [3][2]string{
		{"Beijing Shanghai"},
{"Guangzhou", "Shenzhen"},
{"Chengdu", "Chongqing"},
}
fmt.Println(a) //[[Beijing Shanghai] [Guangzhou Shenzhen] [Chengdu Chongqing]]
fmt.Println(a[2][1]) //Support index value: Chongqing
}

/////////////////////////////////////////////////////////////////////
func main() {
a := [3][2]string{
		{"Beijing Shanghai"},
{"Guangzhou", "Shenzhen"},
{"Chengdu", "Chongqing"},
}
for _, v1 := range a {
for _, v2 := range v1 {
fmt.Printf("%s\t", v2)
}
fmt.Println()
}
}

Leave a Reply

Your email address will not be published.

en_USEnglish