Go中函数中返回变量的数量可变 [英] Variable number of return variables in function in Go

查看:235
本文介绍了Go中函数中返回变量的数量可变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否存在一种实现类似于map getter的功能的方法:它返回返回值作为第一个参数,(可选地分配)第二个值ok作为第二个参数.因此,我需要可以通过以下方式调用的函数f:

I wonder if there is a way to implement a function that behaves similar to map getter: it returns return value as first argument and (optionally assigned) second value ok as second argument. So I need function f that I can call in following ways:

value1 := f(1)
value2, ok := f(2)

推荐答案

不,它不能完成,唯一的选择是返回一个指针并检查它是否为空.

No, it can't be done, the only option is to return a pointer and check if it's nil.

if v := f(10); v != nil {
     //stuff
}

这篇关于Go中函数中返回变量的数量可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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