代码
package main
import (
"fmt"
)
func main() {
fmt.Println("***创建数组***")
var arr1 [3]int = [3]int{1, 2, 3}
fmt.Println(arr1)
var arr2 = [5]int{2, 4, 1, 8, 7}
fmt.Println(arr2)
arr3 := [3]int{3, 2, 1}
fmt.Println(arr3)
arr4 := [...]int{1, 6, 7, 8, 5}
fmt.Println(arr4)
fmt.Println("***遍历数组***")
for i := 0; i < len(arr4); i++ {
fmt.Printf("索引:%d,值:%d\n", i, arr4[i])
}
fmt.Println("-------------------------")
for index, values := range arr4 {
fmt.Printf("索引:%d,值:%d\n", index, values)
}
fmt.Println("***创建二维数组***")
var arr5 [3][3]int = [3][3]int{{1, 3, 5}, {2, 4, 6}, {8, 9, 10}}
fmt.Println(arr5)
fmt.Println("***遍历二维数组***")
for i := 0; i < len(arr5); i++ {
for j := 0; j < len(arr5[i]); j++ {
fmt.Print(arr5[i][j], "\t")
}
fmt.Println()
}
fmt.Println("-------------------------")
for index, value := range arr5 {
for i, v := range value {
fmt.Printf("arr5[%v][%v] = %v\t", index, i, v)
}
fmt.Println()
}
fmt.Println("***创建切片***")
slice1 := arr4[1:3]
fmt.Println(slice1)
slice2 := make([]int, 5, 20)
slice2[1] = 99
slice2[4] = 100
fmt.Println(slice2)
slice3 := []int{1, 3, 5, 7, 9}
fmt.Println(slice3)
fmt.Println("***遍历切片***")
for i := 0; i < len(slice3); i++ {
fmt.Printf("key:%d,value:%d\n", i, slice3[i])
}
fmt.Println("-------------------------")
for k, v := range slice3 {
fmt.Printf("key:%d,value:%d\n", k, v)
}
fmt.Println("***切片知识扩充***")
fmt.Println("改变切片的值")
var intarr [5]int = [5]int{5, 4, 3, 2, 1}
fmt.Println("原数组:", intarr)
var intslice []int = intarr[1:3]
fmt.Println("切片:", intslice)
intslice[1] = 999
fmt.Printf("原数组:%v,切片:%v\n", intarr, intslice)
fmt.Println("append() 函数的使用")
s1 := intarr[:]
s2 := append(s1, 88, 66)
fmt.Println("添加值:", s2)
s := []int{33, 44}
s3 := append(s1, s...)
fmt.Println("添加切片:", s3)
fmt.Println("copy() 函数的使用")
a := []int{5, 6, 7}
b := make([]int, 6)
copy(b, a)
fmt.Println("a复制到b中后:", b)
}
结果