Eka
Eka

Reputation: 15002

How to return an empty value in golang?

I need to return an empty value for a function in golang, my code look something like this.

package main

import (
    "fmt"
)

func main(){
    for i:=0;i<6;i++{
        x,e := test(i)
        fmt.Println(i,x,e)
    }


}

func test(i int)(r int,err error){
    if i%2==0{
        return i,nil
    }else{
        return 
    }
}

and its output

0 0 <nil>
1 0 <nil>
2 2 <nil>
3 0 <nil>
4 4 <nil>
5 0 <nil>

whereas I want this type of output

0 0 <nil>
1 <nil> <nil>
2 2 <nil>
3 <nil> <nil>
4 4 <nil>
5 <nil> <nil>

How to return empty value in golang?

Upvotes: 0

Views: 2980

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51632

"Empty value" is a matter of convention. You have to define what empty value means.

  • Many of the standard library functions return an invalid value to denote empty. For instance, strings.Index returns -1, because all valid values are >=0
  • Functions returning pointer usually return nil
  • There are functions that return pairs of values, one value and one denoting validity. Maps and channels also use this convention:
value, exists:=someMap[key]

Above, if exists is true, then value has a valid value. If exists is false, value is not valid (empty).

  • Many functions return a value and error. If error is non-nil, the value is meaningless.

So in your code, you can do:

func test(i int)(r int,valid bool){
    if i%2==0{
        return i,true
    }else{
        return 0,false
    }
}

Or, if you have an error condition, return a non-nil error from your function and check if there is an error where you called it. If there is an error, whatever the value returned is "empty".

Upvotes: 5

Related Questions