0

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?

3
  • Return empty interface then Commented Jan 20, 2020 at 3:56
  • You can pass the pointer instead of value func test(i *int)(r *int,err error) Commented Jan 20, 2020 at 3:58
  • You cannot. There are no "empty" values in Go Commented Jan 20, 2020 at 5:36

1 Answer 1

5

"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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.