I need confirmation about whether I'm in front of a linter false positive.

181 views
Skip to first unread message

Pablo Caballero

unread,
Aug 14, 2023, 4:54:35 PM8/14/23
to golang-nuts
I started working on a Golang project (from my work). The following pattern makes the company configured linter to complain with:
sloppyReassign: re-assignment to `err` can be replaced with `err := myFunc2()` (gocritic)

func myFunc() error {
...
blah, err := getBlah()
if err != nil {
    return err
}
...
if err = myFunc2; err != nil {
    return err
}
...
}


What bothers me the most is the fact that if I listen to the linter and change the code according to its suggestion I get another complaint saying that I should use the if short version.

Yes, I have found silenced sloppyReassign following this pattern.

What do you think? What linter complaint should I mute? I don't like the idea of a code base polluted with instructions to tell the linter to shut up. Do you think I should suggest stopping using linters? :)

Thank you!

David Finkel

unread,
Aug 14, 2023, 5:36:11 PM8/14/23
to Pablo Caballero, golang-nuts
My recommendation is to stop re-using the "err" variable.
I eliminated missed if err != nil checks in my codebases by using unique names for my error-typed variables. (and reserving the "err" itself for innermost scopes -- short if statements like the second case you have there)
 

Thank you!

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAPxFe-utkjMEVrc3DtTR5rmsiEuK8ZLvA6d228PjnroaxRtBkw%40mail.gmail.com.

Amnon

unread,
Aug 15, 2023, 5:41:59 PM8/15/23
to golang-nuts
I would stop using that particular linter.

And keep calling your error value err. 
It is idiomatic.

Christoph Berger

unread,
Aug 16, 2023, 2:11:26 AM8/16/23
to golang-nuts
The linter complains because the second err occurs in a different scope. "if err = f(); err != nil" scopes this err instance to the if block. It re-uses the err from the outer scope, which might not be intended. 

If you only use either of "err = f(); if err..." or "if err = f(); err..." consistently, the linter should not complain anymore.

And what I personally prefer if multiple error usages occur in the same function is to name the return value: "f() (err error) {...". This pre-defines err for the whole function, and you never need to decide whether to use "err :=" or "err =". Useful if you move code inside the functions around or add new code at the top.

Reply all
Reply to author
Forward
0 new messages