如何通过引用返回片? [英] How to return slice by reference?

查看:154
本文介绍了如何通过引用返回片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过引用返回的片段为空:

 包主

导入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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆