golang slice
程序员文章站
2024-03-01 13:17:10
...
package main
import "fmt"
func main() {
var arr1_ [8]int
var slice1_ []int = arr1_[0:5] // item at index 5 not included!
var slice2_ []int = arr1_[0:4]
arr1_[2] = 4
fmt.Println(slice1_[2])
fmt.Println(slice2_[2])
slice1_[2] = 5
fmt.Println(arr1_[2])
fmt.Println(slice2_[2])
slice2_[2] = 6
fmt.Println(arr1_[2])
fmt.Println(slice1_[2])
for i:=0;i<4;i++{ //当大于等于5时,就会脱离arr1数组,因为重新分配的它关联的数组。
slice2_=append(slice2_,1);
}
slice2_[2] = 8
fmt.Println(arr1_[2])
fmt.Println(slice1_[2])
fmt.Println("")
var arr1 [8]int
var slice1 []int = arr1[1:5] // item at index 5 not included!
var slice2 []int = arr1[1:4]
arr1[3] = 4
fmt.Println(slice1[2])
fmt.Println(slice2[2])
slice1[2] = 5
fmt.Println(arr1[3])
fmt.Println(slice2[2])
slice2[2] = 6
fmt.Println(arr1[3])
fmt.Println(slice1[2])
for i:=0;i<5;i++{ //当大于等于5时,就会脱离arr1数组,因为重新分配的它关联的数组。
slice2=append(slice2,1);
}
slice2[2] = 8
fmt.Println(arr1[3])
fmt.Println(slice1[2])
fmt.Println("")
var ar = [10]int{0,1,2,3,4,5,6,7,8,9}
var a = ar[5:7] // reference to subarray {5,6} - len(a) is 2 and cap(a) is 5
for _,v :=range a{
fmt.Println(v)
}
a = a[0:4] // ref of subarray {5,6,7,8} - len(a) is now 4 but cap(a) is still 5
for _,v :=range a{
fmt.Println(v)
}
}
下一篇: 经典查找算法(java)