dougaxing8673 2017-10-13 09:34
浏览 964
已采纳

如何在golang中返回int或nil?

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.

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?

Here's how it looks for now:

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

Is it good style?

  • 写回答

2条回答 默认 最新

  • douguio0185 2017-10-13 09:43
    关注

    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
    }
    

    Then somewhere you can call Pop as

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

    Take a look at comma, ok idiom.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题