3 ms·
Yea, you are correct in your understanding, but such code is super rare in my experience. In fact, until recently I didn't even know such behavior exists at all
by andreygrehov 6y ago
Yea, you are correct in your understanding, but such code is super rare in my experience. In fact, until recently I didn't even know such behavior exists at all. Answering your question, checking if a pointer is `nil` isn't that common among gophers. A more common idiom is to return both a pointer and an error, and then check if error is not `nil`:
user, err := users.FindByID(id)
if err != nil {
return nil, err
}
If the return value is just a pointer, in my books a nil value should be avoided. I guess what's not cool here is that there are no guarantees. If I'm using a library in which a function returns just a pointer, I sometimes jump in the function's body to check if it ever returns nil so that I don't have to pollute my code with `if` statements. Like, you almost never check for `nil` when dealing with simple factories, eg foo := NewFoo(). However, when it comes to a more complex method calls, it might be safer to add a quick `nil` check and forget about it.