深入理解Go语言的slice
转载请注明出处,原文链接http://tailnode.tk/2017/01/%E... 先看这段代码,结果是 func modify(s []int) { s[0] = 0 } func main() { s := []int{1,2,3} modify(s) fmt.Println(s) } 然后稍微改动一下,再猜一下结果 func pop(s []int) { s = s[:len(s)-1] } func main() { s := []int{1,3} pop(s) fmt.Println(s) } 如果认为输出 我们对中间过程加一些输出,再来看看 func pop(s []int) { fmt.Printf("[pop] s addr:%pn",&s) s = s[:len(s)-1] fmt.Println("[pop] s value:",s) } func main() { s := []int{1,3} fmt.Printf("[main] s addr:%pn",&s) pop(s) fmt.Println("[main] s value:",s) } 运行上面代码输出如下 [main] s addr:0xc082004640 [pop] s addr:0xc0820046c0 [pop] s value: [1 2] [main] s value: [1 2 3] 看到上面的结果,可以知道 下面来看下slice的实现,就能很清楚的了解原因了。 type sliceHeader struct { Length int ZerothElement *byte } 参照这个结构体的定义和下面的说明,就能很清楚地了解开始的两个例子了
那当我们需要将slice做为函数参数传入,并且函数会修改slice时,怎么办呢。这里说三种方法。 func modify(s *[]int) { // do something } 2.把函数内被修改后的slice做为返回值,将函数返回值赋值给原始slice func modify(s []int) []int { // do something return s } func main() { s := []int{1,3} s = modify(s) } 3.将函数做为slice指针的方法 type slice []int func (s *slice) modify() { // do something } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |