go语言切片技巧 go切片操作( 三 )


func test11() {
slice := []int32{}
fmt.Printf("slice的长度为:%d,slice为:%v\n", len(slice), slice)
slice = append(slice, 12, 11, 10, 9)
fmt.Printf("追加后,slice的长度为:%d,slice为:%v\n", len(slice), slice)
slicecp := make([]int32, (len(slice)))
fmt.Printf("slicecp的长度为:%d,slicecp为:%v\n", len(slicecp), slicecp)
copy(slicecp, slice)
fmt.Printf("复制赋值后,slicecp的长度为:%d,slicecp为:%v\n", len(slicecp), slicecp)
}
追加、复制切片,用的是内置函数append和copy , copy函数返回的是最后所复制的元素的数量 。
(5)、内置函数append
内置函数append可以向一个切片后追加一个或多个同类型的其他值 。如果追加的元素数量超过了原切片容量,那么最后返回的是一个全新数组中的全新切片 。如果没有超过 , 那么最后返回的是原数组中的全新切片 。无论如何 , append对原切片无任何影响 。如下示例:
复制代码代码如下:
func test12() {
slice := []int32{1, 2, 3, 4, 5, 6}
slice2 := slice[:2]
_ = append(slice2, 50, 60, 70, 80, 90)
fmt.Printf("slice为:%v\n", slice)
fmt.Printf("操作的切片:%v\n", slice2)
_ = append(slice2, 50, 60)
fmt.Printf("slice为:%v\n", slice)
fmt.Printf("操作的切片:%v\n", slice2)
}
如上,append方法用了2次,结果返回的结果完全不同,原因是第二次append方法追加的元素数量没有超过 slice 的容量 。而无论怎样,原切片slice2都无影响 。结果:
slice为:[1 2 3 4 5 6]
操作的切片:[1 2]
slice为:[1 2 50 60 5 6]
操作的切片:[1 2]
golang 切片在函数传递背景: 切片当参数传递时,无法append
原因: go语言中切片是地址传递,test函数添加的1,2,3后被分配了新的地址 , s切片还是指向原来的地址,a和s内存地址不一样
解决方法:推荐方法2
1.在test函数返回新的切片,main函数接受返回结果
golang-101-hacks(12)——切片作为函数参数传递注:本文是对 golang-101-hacks 中文翻译 。
在Go语言中,函数参数是值传递 。使用slice作为函数参数时,函数获取到的是slice的副本:一个指针,指向底层数组的起始地址 , 同时带有slice的长度和容量 。既然各位熟知数据存储的内存的地址 , 现在可以对切片数据进行修改 。让我们看看下面的例子:
In Go, the function parameters are passed by value. With respect to use slice as a function argument, that means the function will get the copies of the slice: a pointer which points to the starting address of the underlying array, accompanied by the length and capacity of the slice. Oh boy! Since you know the address of the memory which is used to store the data, you can tweak the slice now. Let's see the following example:
运行结果如下
由此可见,执行modifyValue函数,切片s的元素发生了变化 。尽管modifyValue函数只是操作slice的副本,但是任然改变了切片的数据元素,看另一个例子:
You can see, after running modifyValue function, the content of slice s is changed. Although the modifyValue function just gets a copy of the memory address of slice's underlying array, it is enough!
See another example:
The result is like this:
而这一次 , addValue函数并没有修改main函数中的切片s的元素 。这是因为它只是操作切片s的副本,而不是切片s本身 。所以如果真的想让函数改变切片的内容,可以传递切片的地址:
This time, the addValue function doesn't take effect on the s slice in main function. That's because it just manipulate the copy of the s, not the "real" s.
So if you really want the function to change the content of a slice, you can pass the address of the slice:

推荐阅读