In Go, we often write code with declaration in if statement and also return err. Like this:
if res, err := getResult(); err != nil {
return err
} else {
fmt.Println(res)
// do something with res
}
But the linter always tells me should drop the else block after return:
⚠ https://revive.run/r#indent-error-flow if block ends with a return statement, so drop this else and outdent its block (move short variable declaration to its own line if necessary)
The code snippet should looks like this to meet the suggestion:
res, err := getResult()
if err != nil {
return err
}
fmt.Println(res)
// do something with res
It seems that we should avoid to use the declaration in if statements.
So what is the correct Go style? And what should I do with the declaration in if statements?
The section about
ifin Effective Go provides some guidance about this:If you adhere to this style, and if you intend to use the non-
errorresults in your "happy path", you simply cannot declare the function's results as variables in the simple statement that can precede the condition of theifstatement; you have no choice but to put that variable declaration before theif. However, in cases where the function only returns anerror(or you don't care about its other results), you're free to put the variable declaration in theif: