1. 程式人生 > 其它 >go切片的能夠修改陣列

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()
}

寫入自己的部落格中才能記得長久