golang的數組的append操作


今天學習了一下數組的操作,寫了如下代碼

	test8_3 := [] int {0,1,2,3,4,5,6,7,8,9}

	a := test8_3[2:]
	//b := test8_3[:6]
	//c := test8_3[2:6]
	fmt.Println("old A",a,len(a),cap(a),reflect.TypeOf(a))
	//old A [2 3 4 5 6 7 8 9] 8 8 []int

	fmt.Println("old T",test8_3,len(test8_3),cap(test8_3))
	//old T [0 1 2 3 4 5 6 7 8 9] 10 10
	
	a = append(a,10)
	a[2] = 100
	fmt.Println("new A",a,len(a),cap(a))
	//new A [2 3 100 5 6 7 8 9 10] 9 16
	fmt.Println("new T",test8_3,len(test8_3),cap(test8_3))
	//new T [0 1 2 3 4 5 6 7 8 9] 10 10

 

為何我修改了a這個切片的第二個元素的值,但是對原始的切片沒有影響呢? 之前學的不這樣啊,對數組的切片實際還是對原來數組的引用,如果修改切片后的數組,是對原數組是有影響的啊,但是這里為什么沒有?

 

突然看到,我這里有一個a切片的append的操作,會不會append操作后,a切片就不是之前的a切片了,也就不是對原始數組的引用了?如何證明的,那么我們就打印一下切片的首個元素的內存地址把

	test8_3 := [] int {0,1,2,3,4,5,6,7,8,9}

	a := test8_3[2:]
	//b := test8_3[:6]
	//c := test8_3[2:6]
	fmt.Println("old A",a,len(a),cap(a),reflect.TypeOf(a),&a[0])
	//old A [2 3 4 5 6 7 8 9] 8 8 []int 0xc000068060

	fmt.Println("old T",test8_3,len(test8_3),cap(test8_3))
	//old T [0 1 2 3 4 5 6 7 8 9] 10 10

	a = append(a,10)
	a[2] = 100
	fmt.Println("new A",a,len(a),cap(a),&a[0])
	//new A [2 3 100 5 6 7 8 9 10] 9 16 0xc000096080
	fmt.Println("new T",test8_3,len(test8_3),cap(test8_3))
	//new T [0 1 2 3 4 5 6 7 8 9] 10 10

 

我們看到前后兩次打印a變量的第一個元素的內存地址是不一樣的,所以證明了我的懷疑

 

然后我把append這個操作注釋掉,在確認下前后兩次打印的內存地址是否一樣

	test8_3 := [] int {0,1,2,3,4,5,6,7,8,9}

	a := test8_3[2:]
	//b := test8_3[:6]
	//c := test8_3[2:6]
	fmt.Println("old A",a,len(a),cap(a),reflect.TypeOf(a),&a[0])
	//old A [2 3 4 5 6 7 8 9] 8 8 []int 0xc00000c240

	fmt.Println("old T",test8_3,len(test8_3),cap(test8_3))
	//old T [0 1 2 3 4 5 6 7 8 9] 10 10

	//a = append(a,10)
	a[2] = 100
	fmt.Println("new A",a,len(a),cap(a),&a[0])
	//new A [2 3 100 5 6 7 8 9] 8 8 0xc00000c240
	fmt.Println("new T",test8_3,len(test8_3),cap(test8_3))
	//new T [0 1 2 3 100 5 6 7 8 9] 10 10

 

證明我們的猜測,這次前后兩次的內存地址是一樣的,同樣,修改切片后的元素的值,對原始數組也產生了影響

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM