如何通过引用返回片? [英] How to return slice by reference?
本文介绍了如何通过引用返回片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通过引用返回的片段为空:
包主
导入fmt
func GetItems(items * [] string){
list:= make([] string,0)
list = append(list,ok)
items& list
func main(){
var items [] string
GetItems(& items)
fmt.Print( len(items))// expect 1 here,but got 0
}
如何通过引用从函数返回切片?
解决方案
通过分配给项目
,你改变项目
点数,而不是 items =& list
write * items = list
。
The returned slice by reference is empty:
package main
import "fmt"
func GetItems(items *[]string) {
list := make([]string, 0)
list = append(list, "ok")
items = &list
}
func main() {
var items []string
GetItems(&items)
fmt.Print(len(items)) // expect 1 here, but got 0
}
How to return the slice from the function by reference?
解决方案
By assigning to items
, you alter where items
points, not the value items
points to. To do the latter, instead of items = &list
write *items = list
.
这篇关于如何通过引用返回片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文