Returning nil types

Please see the following link for the code in question but here is my question. If you review the code on line 24 you’ll see a commented out type and on line 25 you’ll notice that I’m trying to return nil because I didn’t find the entry in the map I was looking for. This is a very basic set of code to show my point and I realize it is pointless in its current form. But my question is this:

In my example I am looking inside a map in order to return a user structure of the user they are looking for. If I do not find it then I wanted to just return a nil user so they would immediately know it wasn’t there. Instead I am able to return an error type of nil but I get a compiler error if I attempt to return a user type of nil which confuses me. So instead I’m being forced to create a usertype on line 24 and send it back with none of its fields set which is fine but seems odd to me.

Why can I return a nil error but not a nil user?

Thanks,

https://play.golang.org/p/w94ptl5iA8d

1 Like

user is a struct, structs can’t be nil only pointers and interfaces can. error is an interface and therefore can be nil.

1 Like

Thanks. Is what I did the proper way to handle it? Just passing back an empty user type?

1 Like

When returning an error value then it’s idiomatic to return the other types zero-value.

For the user struct, that’s user{}.

1 Like

Thanks for the help.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.