如何在golang中返回int或nil? [英] How to return int or nil in golang?

查看:140
本文介绍了如何在golang中返回int或nil?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java开发人员,正在学习Go.我正在为LIFO堆栈编写简单的"pop"操作.问题是堆栈中没有值时的返回值.在Java中,我可以在肯定的情况下返回wrapper(Integer),并且在没有值的情况下返回null.从我的角度来看这很自然.

I'm a java developer and I am learning Go. I'm writing simple 'pop' operation for a LIFO stack. The question is with the return value when there are no values in the stack. In java, I'm able to return a wrapper(Integer) in the positive case and null when there are no values. It's natural from my perspective.

我该如何在Go中做类似的事情?是否有用于基本体的结构包装器?我是否需要返回两个值(第二个将指示错误代码)?还是我需要抛出异常?

How can I do something similar in Go? Are there any struct wrappers for primitives? Do I need to return two values(the second will indicate error code)? Or do I need to throw an exception?

这是现在的样子:

func (s *stack) Pop() (int, bool)  {
    if s.size == 0 {
        return 0, true
    }
    s.size--
    val := s.stack[s.size]
    return val, false
}

这是好风格吗?

推荐答案

由于数字不能为 nil ,因此除非整数,否则您不能返回 nil 您将返回值定义为指针.Go中的惯用解决方案是定义您的方法以返回多个值,例如

Since a number can't be nil, you can't return nil for integer, unless you define the return value as a pointer. The idiomatic solution in Go is by defining your method to return more than one values, e.g.

func (s *stack) Pop() (int, bool) {
    //does not exists
    if ... {
        return 0, false
    }

    //...

    //v is the integer value
    return v, true
}

然后在某个地方您可以将 Pop 称为

Then somewhere you can call Pop as

s := &stack{}
if v, ok := s.Pop(); ok {
    //the value exists
}

看看逗号,好的用法.

这篇关于如何在golang中返回int或nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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