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

如何在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?

图片转代码服务由CSDN问答提供 功能建议

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

如何在Go中执行类似的操作? 是否有用于原语的结构包装器? 我是否需要返回两个值(第二个将指示错误代码)? 还是我需要抛出异常?

这是现在的样子:

  func(s * stack)Pop()  (int,bool){
,如果s.size == 0 {
返回0,true 
} 
 s.size-
 val:= s.stack [s.size] 
返回val,  false 
} 
   
 
 

样式好吗?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dtl19910708 2017-10-13 09:41

    There's no try/catch constructs in Go, so you can't rely on that.

    Go has instead a nice feature of allowing multiple return values. And their error handling is built on that.

    So the canonical way to deal with the possibility of an exception is to return both a value and an error. After the operation, the error is checked and acted upon, ignoring the value. In your case you can keep the value as an int, and use a default value of 0 in the case of an error. Since clients would hopefully ignore the value in that case and do something about the error.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题