GO learning - 008 array


GO learning - 008 array

test1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package main

import "fmt"

func printArray(myArray [4]int) {
for index, value := range myArray {
fmt.Println("index = ", index, " value = ", value)
}
}

func main() {
var myArray1 [10]int

myArray2 := [10]int{1, 2, 3, 4}
myArray3 := [4]int{11, 22, 33, 44}

for i := 0; i < len(myArray1); i++ {
fmt.Println(myArray1[i])
}

for index, value := range myArray2 {
fmt.Println("index = ", index, " value = ", value)
}

fmt.Printf("myArray1 types = %T\n", myArray1)
fmt.Printf("myArray2 types = %T\n", myArray2)
fmt.Printf("myArray3 types = %T\n", myArray3)

printArray(myArray3) //传1或2会报错

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
0
0
0
0
0
0
0
0
0
0
index = 0 value = 1
index = 1 value = 2
index = 2 value = 3
index = 3 value = 4
index = 4 value = 0
index = 5 value = 0
index = 6 value = 0
index = 7 value = 0
index = 8 value = 0
index = 9 value = 0
myArray1 types = [10]int
myArray2 types = [10]int
myArray3 types = [4]int
index = 0 value = 11
index = 1 value = 22
index = 2 value = 33
index = 3 value = 44

test2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import "fmt"

func printArray(myArray []int) {
for _, value := range myArray {
fmt.Println("value = ", value)
}

myArray[0] = 100
}

func main() {

myArray := []int{1, 2, 3, 4}

fmt.Printf("myArray type is %T\n", myArray)

printArray(myArray)

fmt.Println("===")
for _, value := range myArray {
fmt.Println(value)
}
}
1
2
3
4
5
6
7
8
9
10
myArray type is []int
value = 1
value = 2
value = 3
value = 4
===
100
2
3
4

Author: Liang Junyi
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source Liang Junyi !
  TOC