go语言切片作为参数传递 golang切片传参

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:
运行结果如下
【go语言切片作为参数传递 golang切片传参】 由此可见,执行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:
运行结果如下
Golang 中数组(Array)和切片(Slice)的区别 Go 中数组的长度是不可改变的 , 而 Slice 解决的就是对不定长数组的需求 。他们的区别主要有两点 。
数组:
切片:
注意 1
虽然数组在初始化时也可以不指定长度,但 Go 语言会根据数组中元素个数自动设置数组长度,并且不可改变 。切片通过 append 方法增加元素:
如果将 append 用在数组上,你将会收到报错:first argument to append must be slice 。
注意 2
切片不只有长度(len)的概念,同时还有容量(cap)的概念 。因此切片其实还有一个指定长度和容量的初始化方式:
这就初始化了一个长度为3 , 容量为5的切片 。
此外,切片还可以从一个数组中初始化(可应用于如何将数组转换成切片):
上述例子通过数组 a 初始化了一个切片 s 。
当切片和数组作为参数在函数(func)中传递时,数组传递的是值,而切片传递的是指针 。因此当传入的切片在函数中被改变时,函数外的切片也会同时改变 。相同的情况,函数外的数组则不会发生任何变化 。
golang 切片在函数传递背景: 切片当参数传递时,无法append
原因: go语言中切片是地址传递,test函数添加的1,2,3后被分配了新的地址 , s切片还是指向原来的地址,a和s内存地址不一样
解决方法:推荐方法2
1.在test函数返回新的切片,main函数接受返回结果
go语言切片作为参数传递的介绍就聊到这里吧,感谢你花时间阅读本站内容 , 更多关于golang切片传参、go语言切片作为参数传递的信息别忘了在本站进行查找喔 。

    推荐阅读