一、类型
数组是值类型,将一个数组赋值给另一个数组时,传递的是一份拷贝。
切片是引用类型,切片包装的数组称为该切片的底层数组。
我们来看一段代码
//a是一个数组,注意数组是一个固定长度的,初始化时候必须要指定长度,不指定长度的话就是切片了 a := [3]int{1, 2, 3} //b是数组,是a的一份拷贝 b := a //c是切片,是引用类型,底层数组是a c := a[:] for i := 0; i二、make
make 只能用于 slice , map 和 channel , 所以下面一段代码生成了一个 slice ,是引用类型
s1 := make([]int, 0, 3) for i := 0; i三、当对slice append 超出底层数组的界限时
//n1是n2的底层数组 n1 := [3]int{1, 2, 3} n2 := n1[0:3] fmt.Println("address of items in n1: ") for i := 0; i四、引用“失效”
实现了删除 slice 最后一个 item 的函数
func rmLast(a []int) { fmt.Printf("[rmlast] the address of a is %p", a) a = a[:len(a)-1] fmt.Printf("[rmlast] after remove, the address of a is %p", a) }调用此函数后,发现原来的 slice 并没有改变
func main() { xyz := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} fmt.Printf("[main] the address of xyz is %p\n", xyz) rmLast(xyz) fmt.Printf("[main] after remove, the address of xyz is %p\n", xyz) fmt.Printf("%v", xyz) //[1 2 3 4 5 6 7 8 9] }打印出来的结果如下:
[main] the address of xyz is 0xc2080365f0 [rmlast] the address of a is 0xc2080365f0 [rmlast] after remove, the address of a is 0xc2080365f0 [main] after remove, the address of xyz is 0xc2080365f0 [1 2 3 4 5 6 7 8 9]这里直接打印了 slice 的指针值,因为 slice 是引用类型,所以指针值都是相同的,我们换成打印 slice 的地址看下
func rmLast(a []int) { fmt.Printf("[rmlast] the address of a is %p", &a) a = a[:len(a)-1] fmt.Printf("[rmlast] after remove, the address of a is %p", &a) } func main() { xyz := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} fmt.Printf("[main] the address of xyz is %p\n", &xyz) rmLast(xyz) fmt.Printf("[main] after remove, the address of xyz is %p\n", &xyz) fmt.Printf("%v", xyz) //[1 2 3 4 5 6 7 8 9] }结果:
[main] the address of xyz is 0xc20801e1e0 [rmlast] the address of a is 0xc20801e200 [rmlast] after remove, the address of a is 0xc20801e200 [main] after remove, the address of xyz is 0xc20801e1e0 [1 2 3 4 5 6 7 8 9]这次可以看到 slice 作为函数参数传入函数时,实际上也是拷贝了一份 slice ,因为 slice 本身是个指针,所以从现象来看, slice 是引用类型
总结
以上就是这篇文章的全部内容,希望对大家的学习或者工作带来一定的帮助,如果有疑问大家可以留言交流。
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did18695