Is it bad practice to reset an error in golang?

15,971

It's not bad practice to reset an error variable, if that's what you want to do.

It is bad practice to set variables that aren't used later--and that's what the warning is about.

There's probably never a reason to reset an error as you are doing, since after the if block err will always be nil.

It does make sense if you're only resetting in some cases. A common example:

result, err := db.Query(...)
if err == sql.ErrNoRows {
    err = nil // Ignore not-found rows
}
if err != nil {
    return err // But return all other errors
}
Share:
15,971
jonhadfield
Author by

jonhadfield

Updated on June 17, 2022

Comments

  • jonhadfield
    jonhadfield almost 2 years

    When parsing a string as text, I want any non-parseable string to result in a zero time and then carry on.

    passwordLastUsed, err = time.Parse(time.RFC3339, record[lastUsed])
    if err != nil {
        err = nil
        passwordLastUsed = time.Time{}
    }
    

    This code looks a bit messy and the 'ineffassign' linter returns this for the 'err = nil' statement:

    warning: ineffectual assignment to err (ineffassign)

    Is there a better way of handling this or should I just ignore the linter?

  • jonhadfield
    jonhadfield over 6 years
    That makes sense, thanks. I am using it later, so I think the linter is incorrect in this specific case.
  • Flimzy
    Flimzy over 6 years
    No, the linter is correct. You may be using it later, but only after it's being unconditionally reset again.
  • jonhadfield
    jonhadfield over 6 years
    Ok, I understand now. I added another check "if err != nil" immediately after that snippet and it was no longer repeated as ineffectual. As you said, because err was always equal to nil after that piece of code, and the next piece of code reset the value of err, it really was ineffectual.