Skip to content

Commit

Permalink
treat err assignments as a simple error check
Browse files Browse the repository at this point in the history
We considered the following pattern a "simple" error check,
where err was declared with `:=` and immediately followed by an if:

    x, err := f()

    if err != nil {...}

We would then remove the empty line before the error check.
However, we wouldn't do the same if x and err were already declared:

    x, err = f()

    if err != nil {...}

The second form is still relatively common, and there's no good reason
for the check to treat the two cases differently.

Fixes #271.
  • Loading branch information
mvdan committed Aug 23, 2023
1 parent 9a108c1 commit 025a91f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
4 changes: 2 additions & 2 deletions format/format.go
Expand Up @@ -866,9 +866,9 @@ func (f *fumpter) stmts(list []ast.Stmt) {
continue // not an if following another statement
}
as, ok := list[i-1].(*ast.AssignStmt)
if !ok || as.Tok != token.DEFINE ||
if !ok || (as.Tok != token.DEFINE && as.Tok != token.ASSIGN) ||
!identEqual(as.Lhs[len(as.Lhs)-1], "err") {
continue // not "..., err := ..."
continue // not ", err :=" nor ", err ="
}
be, ok := ifs.Cond.(*ast.BinaryExpr)
if !ok || ifs.Init != nil || ifs.Else != nil {
Expand Down
11 changes: 11 additions & 0 deletions testdata/script/newline-errcheck.txtar
Expand Up @@ -53,6 +53,12 @@ func f() {
panic(err)
}
}

n5, err = Do2()

if err != nil {
panic(err)
}
}
-- foo.go.golden --
package p
Expand Down Expand Up @@ -101,4 +107,9 @@ func f() {
panic(err)
}
}

n5, err = Do2()
if err != nil {
panic(err)
}
}

0 comments on commit 025a91f

Please sign in to comment.