gomultiple-return-values

Return 1 value to the function with multiple return values in golang


I want to return just 1 value to the function with multiple return values. I tried this:

func myFunc() (int, int){
    return _, 3
}

But it didn't work and raised this error: cannot use _ as value

I already know that It's possible to receive one of the returned values.

Is there any way to return just 1 value?


Solution

  • Use the zero value for the other return parameters:

    func myFunc() (int, int){
        return 0, 3
    }
    

    If you use named result parameters, you may also do:

    func myFunc() (x, y int){
        y = 3
        return
    }
    

    In this case x will also be the zero value of its type, 0 in case of int.

    You could also write a helper function which adds a dummy return value, e.g.:

    func myFunc() (int, int) {
        return extend(3)
    }
    
    func extend(i int) (int, int) {
        return 0, i
    }
    

    But personally I don't think it's worth it. Just return the zero value for "unused" return parameters.