go语言切片的底层 go语言切片排序( 二 )


func test10() {
slice0 := []string{"a", "b", "c", "d", "e"}
fmt.Println("\n~~~~~~元素遍历~~~~~~")
for _, ele := range slice0 {
fmt.Print(ele, " ")
ele = "7"
}
fmt.Println("\n~~~~~~索引遍历~~~~~~")
for index := range slice0 {
fmt.Print(slice0[index], " ")
}
fmt.Println("\n~~~~~~元素索引共同使用~~~~~~")
for index, ele := range slice0 {
fmt.Print(ele, slice0[index], " ")
}
fmt.Println("\n~~~~~~修改~~~~~~")
for index := range slice0 {
slice0[index] = "9"
}
fmt.Println(slice0)
}
如上,前三种循环使用了不同的for range循环 , 当for后面,range前面有2个元素时 , 第一个元素代表索引,第二个元素代表元素值,使用 “_” 则表示忽略,因为go语言中,未使用的值会导致编译错误 。
只有一个元素时,该元素代表索引 。
只有用索引才能修改元素 。如在第一个遍历中,赋值ele为7,结果没有作用 。因为在元素遍历中,ele是值传递,ele是该切片元素的副本,修改它不会影响原本值,而在第四个遍历——索引遍历中,修改的是该切片元素引用的值,所以可以修改 。
结果为:
~~~~~~元素遍历~~~~~~
a b c d e
~~~~~~索引遍历~~~~~~
a b c d e
~~~~~~元素索引共同使用~~~~~~
aa bb cc dd ee
~~~~~~修改~~~~~~
[9 9 9 9 9]
(4)、追加、复制切片:
复制代码代码如下:
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-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:

推荐阅读