Skip to content

Commit f35518a

Browse files
committed
数组和切片完成
1 parent 015e2f5 commit f35518a

File tree

4 files changed

+581
-4
lines changed

4 files changed

+581
-4
lines changed

Diff for: demo/array-001.go

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func main() {
6+
arr := [...]float64{23.2,34.12,45.22,55.6}
7+
fmt.Println("length of a is ",len(arr)); // print 4
8+
9+
for i := 0; i < len(arr); i++ { //looping from 0 to the length of the array
10+
fmt.Printf("%d th element of a is %.2f\n", i, arr[i])
11+
}
12+
13+
sum := float64(0);
14+
for i,v := range arr {
15+
fmt.Printf("%d the element of a is %.2f\n ",i,v);
16+
sum += v
17+
}
18+
fmt.Println("\n of all element of a ",sum);
19+
}

Diff for: demo/array-002.go

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func printarray(a [3][2]string) {
8+
for _, v1 := range a {
9+
for _, v2 := range v1 {
10+
fmt.Printf("%s ", v2)
11+
}
12+
fmt.Printf("\n")
13+
}
14+
}
15+
16+
func main() {
17+
a := [3][2]string{
18+
{"lion", "tiger"},
19+
{"cat", "dog"},
20+
{"pigeon", "peacock"}, //this comma is necessary. The compiler will complain if you omit this comma
21+
}
22+
printarray(a)
23+
var b [3][2]string
24+
b[0][0] = "apple"
25+
b[0][1] = "samsung"
26+
b[1][0] = "microsoft"
27+
b[1][1] = "google"
28+
b[2][0] = "AT&T"
29+
b[2][1] = "T-Mobile"
30+
fmt.Printf("\n")
31+
printarray(b)
32+
}

Diff for: demo/slice-001.go

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func main() {
8+
arr := [5]int{23,44,55,66,77}
9+
var b []int = arr[1:4]
10+
fmt.Println(b)
11+
c :=[]int{7,8,9,99,12}
12+
fmt.Println(c)
13+
14+
darr := [...]int{57, 89, 90, 82, 100, 78, 67, 69, 59}
15+
dslice := darr[2:5]
16+
fmt.Println("array before",darr)
17+
for i := range dslice {
18+
dslice[i]++
19+
}
20+
fmt.Println("array after ",darr)
21+
22+
fruitarray := [...]string{"apple", "orange", "grape", "mango", "water melon", "pine apple", "chikoo"}
23+
fruitslice := fruitarray[1:3]
24+
fmt.Printf("length of slice %d capacity %d \n", len(fruitslice), cap(fruitslice)) //length of is 2 and capacity is 6
25+
26+
var names []string //zero value of a slice is nil
27+
if names == nil {
28+
fmt.Println("slice is nil going to append")
29+
names = append(names, "John", "Sebastian", "Vinay")
30+
fmt.Println("names contents:",names)
31+
}
32+
33+
sl1 := []string{"apple","orange","tag"}
34+
sl2 := []string{"fruit","person"}
35+
36+
sl3 := append(sl1,sl2...);
37+
fmt.Println("sl3 : ",sl3)
38+
}

0 commit comments

Comments
 (0)