好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

golang切片append方法不会改变内存地址

请看测试代码:

package main

import "fmt"

func main() {
	var s []int
	printSlice(s)
	fmt.Printf("%p\n", &s)
	// 添加一个空切片
	s = append(s, 0)
	printSlice(s)
	fmt.Printf("%p\n", &s)

	// 这个切片会按需增长
	s = append(s, 1)
	printSlice(s)
	fmt.Printf("%p\n", &s)

	// 可以一次性添加多个元素
	s = append(s, 2, 3, 4)
	printSlice(s)
	fmt.Printf("%p\n", &s)
}

func printSlice(s []int) {
	fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

返回结果:

len=0 cap=0 []
0xc0000ae018
len=1 cap=1 [0]
0xc0000ae018
len=2 cap=2 [0 1]
0xc0000ae018
len=5 cap=6 [0 1 2 3 4]
0xc0000ae018

由此可见,内存地址并没有改变。

查看更多关于golang切片append方法不会改变内存地址的详细内容...

  阅读:58次