go切片的能够修改数组
点击查看代码
package main
import (
"fmt"
)
func testSlice() {
var a []int
if a == nil {
fmt.Printf("a is nil\n")
} else {
fmt.Printf("a=%v\n", a)
}
//a[0] = 200 // 空切片不能这样直接赋值
}
func testSlice1() {
a := [5]int{1, 2, 3, 4, 5}
var b []int
b = a[1:4]
fmt.Printf("slice b:%v\n", b)
fmt.Printf("b[0]=:%d\n", b[0])
fmt.Printf("b[1]=:%d\n", b[1])
fmt.Printf("b[2]=:%d\n", b[2])
// fmt.Printf("b[2]=:%d\n", b[3]) panic: runtime error: index out of range [3] with length 3
}
func testSlice2() {
a := []int{1, 2, 3, 4, 5}
fmt.Printf("slice a:%v type of a:%T\n", a, a)
// fmt.Printf("b[2]=:%d\n",b[3])
}
func testSlice3() {
a := [5]int{1, 2, 3, 4, 5}
var b []int
b = a[1:4]
fmt.Printf("slice b:%v\n", b)
// c := a[1:len(a)]
c := a[1:]
fmt.Printf("slice c:%v\n", c)
//d := a[0:3]
d := a[:3]
fmt.Printf("slice d:%v\n", d)
// e := a[0:len(a)]
e := a[:]
fmt.Printf("slice e:%v\n", e)
}
//切片能修改数组的引用
func testSlice4() {
a := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11} // [...]int 表示数组,长度自动推导
fmt.Printf("array a:%v type of a:%T\n", a, a)
b := a[2:5] // 数组经过[2:5]切断了变成切片slice
fmt.Printf("slice b:%v type of b:%T\n", b, b)
b[0] = b[0]+10
b[1] = b[1]+20
b[2] = b[2]+30
fmt.Printf("after modify slice a,array a:%v type of a:%T\n",a,a)
fmt.Printf("after modify slice b,array b:%v type of b:%T\n",b,b)
for index,val :=range b{
fmt.Printf("b[%d]=%d\n",index,val)
}
fmt.Printf("after range modify slice a,array a:%v type of a:%v\n",a,a)
for index := range b {
b[index] = b[index] + 10
fmt.Printf("b[%d]=%d\n", index, b[index])
}
fmt.Printf("after modify slice a,array a:%v type of a:%T\n", a, a)
}
func testSlice5() {
numa := [3]int{78, 79, 80}
//创建一个切片,包含整个数组的所有元素
nums1 := numa[:]
nums2 := numa[:]
fmt.Println("array before change 1", numa)
nums1[0] = 100
fmt.Println("array after modification to slice numsa", nums1, numa)
nums2[1] = 101
fmt.Println("array after modification to slice nums2", nums2, numa)
}
func main() {
testSlice()
testSlice1()
testSlice2()
//testSlice3()
//testSlice4()
//testSlice5()
}
写入自己的博客中才能记得长久