Reputation: 15002
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
Reputation: 51632
"Empty value" is a matter of convention. You have to define what empty value means.
strings.Index
returns -1, because all valid values are >=0nil
value, exists:=someMap[key]
Above, if exists
is true, then value
has a valid value. If exists
is false
, value
is not valid (empty).
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