Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return int or nil in golang?

Tags:

go

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?

like image 549
the_kaba Avatar asked Oct 13 '17 09:10

the_kaba


2 Answers

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.

like image 135
putu Avatar answered Nov 13 '22 01:11

putu


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.

like image 43
Horia Coman Avatar answered Nov 13 '22 01:11

Horia Coman