Go中的数组切片的使用总结
代码示例
package main
import "fmt"
func main(){
fmt.Println("Hello, world")
array := [5]int{1,2,3,4,5}
fmt.Println("Traverse func 1 --->")
for i:= 0; i < len(array); i++ {
fmt.Printf("%d\t",array[i])
}
fmt.Println()
for i, v := range array {
fmt.Printf("index %d is %d\n", i, v)
}
modifyArray(array)
fmt.Println("In main func(), array values -->", array)
useSlice()
}
func modifyArray(array [5]int){
array[0] = 12
fmt.Println("In Modify func(), array values -->", array)
}
func useSlice(){
var myArr [3]int32 = [3]int32{23,1,3}
var mySlice []int32 = myArr[:]
fmt.Println("Elements of myArr is")
for _, v := range myArr {
fmt.Printf("%d\t", v)
}
fmt.Println()
fmt.Println("\nElement of mySlice is ")
for _, v := range mySlice {
fmt.Printf("%d\t", v)
}
fmt.Println()
fmt.Println("直接创建数组切片")
mySliceOne := make([]int, 5, 10)
fmt.Println("\nmySliceOne is ", mySliceOne)
mySliceTwo := []int{1,2,3,43,23}
fmt.Println("\nmySliceTwo is ", mySliceTwo)
for _, v := range mySliceTwo {
fmt.Printf("%d\t", v)
}
myNewSlice := make([]int, 5, 10)
fmt.Println("myNewSlice is ", myNewSlice)
fmt.Println("len(myNewSlice) is ", len(myNewSlice))
fmt.Println("cap(myNewSlice) is ",cap(myNewSlice))
myNewSlice = append(myNewSlice, 12, 12 , 23)
fmt.Println("after append 5 elements in slice, results is ", myNewSlice)
subSlice := []int{12,2,1}
myNewSlice = append(myNewSlice, subSlice...)
fmt.Println("after append other slice in slice, results is ", myNewSlice)
oldSlice := []int{12,23,12}
newSlice := oldSlice[1:2]
fmt.Println("newSlice is ", newSlice)
s1 := []int{1,2,34,4,5,6}
s2 := []int{4,21,1}
fmt.Println("\ns2 is ", s2)
copy(s2, s1)
fmt.Println("copy elements of s1 to s2 is ", s2)
fmt.Println("\ns1 is ", s1)
copy(s1, s2)
fmt.Println("copy elements of s2 to s1 is ", s1)
}
输出结果
Hello, world
Traverse func 1 --->
1 2 3 4 5
index 0 is 1
index 1 is 2
index 2 is 3
index 3 is 4
index 4 is 5
In Modify func(), array values --> [12 2 3 4 5]
In main func(), array values --> [1 2 3 4 5]
Elements of myArr is
23 1 3
Element of mySlice is
23 1 3
直接创建数组切片
mySliceOne is [0 0 0 0 0]
mySliceTwo is [1 2 3 43 23]
1 2 3 43 23 myNewSlice is [0 0 0 0 0]
len(myNewSlice) is 5
cap(myNewSlice) is 10
after append 5 elements in slice, results is [0 0 0 0 0 12 12 23]
after append other slice in slice, results is [0 0 0 0 0 12 12 23 12 2 1]
newSlice is [23]
s2 is [4 21 1]
copy elements of s1 to s2 is [1 2 34]
s1 is [1 2 34 4 5 6]
copy elements of s2 to s1 is [1 2 34 4 5 6]