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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器