top | item 44172489

(no title)

adamrt | 9 months ago

Any time I write "if err == nil" I write // inverted just to make it stick out. It would be nice if it was handled by the language but just wanted to share a way to at least make it a bit more visible.

    if err == nil { // inverted
        return err
    }

discuss

order

hnlmorg|9 months ago

I do something similar. I leave a comment but with a short comment why it’s inverted.

It’s usually pretty obvious why: eg

    if err == nil { 
         // we can exit early because we don’t need to keep retrying
But it at least saves me having to double check the logic of the code each time I reread the code for the first time in a while.

macintux|9 months ago

I know diddly/squat about Go, but from similar patterns in aeons past, would "nil == err" work as a way to make it stand out?

haiku2077|9 months ago

Just tried this and it appears to be valid in the compiler, formatter and golangci-lint

umanwizard|9 months ago

Something slightly more elegant (in my subjective opinion) you could do is write

  if !(err != nil) {

vhcr|9 months ago

Would be nice if code editors colored it differently so it's easier to see.

prerok|9 months ago

return nil

would be clearer, I think. Seems like it's the same but would color differently in my editor.