Shorhand if else?

Hello,
I’m new in Go and I understand what the code does but would love an explanation about how to express what we do here and the logic behind why we do it like that.

if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}

If I understand you correctly, are you asking why someone would write this:

if err := r.ParseForm(); err != nil {
    fmt.Fprintf(w, "ParseForm() err: %v", err)
    return
}

instead of this:

err := r.ParseForm()
if err != nil {
    fmt.Fprintf(w, "ParseForm() err: %v", err)
    return
}

And if so, my answer would be that the only difference is that after the first block of code, there is no err variable outside of the if’s scope, but in the second one, the err is defined outside of the if’s scope, so there’s still an err variable after the if’s closing } brace. One is not inherently better than the other; it depends on the other code around it.

Or maybe I misunderstood, in which case, could you rephrase your question?

At first I was not clear with myself but you helped me anyway! Thanks for the response!

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