ARTICLE AD BOX
In this specific case, you actually can't use := as _ is not treated as a new variable. In this example you must use = and err will be overwritten (reassigned, not shadowed).
It is only allowed to use := if capturing another, not-previously defined variable except for _ or an error (in other words, there must be at least one newly-defined variable which is not _ , e.g x, y := func1() ; x, z := func2() is ok).
Some examples:
func err1() error { return fmt.Errorf("err1") } func err2() error { return fmt.Errorf("err2") } func main() { err := err1() err := err2() // error: no new variables on left side of := fmt.Println(err) } func err1() (int, error) { return 1, fmt.Errorf("err1") } func err2() (int, error) { return 2, fmt.Errorf("err2") } func main() { _, err := err1() _, err := err2() // error: no new variables on left side of := fmt.Println(err) } func err1() (int, error) { return 1, fmt.Errorf("err1") } func err2() (int, error) { return 2, fmt.Errorf("err2") } func main() { x, err := err1() y, err := err2() fmt.Println(x, y, err) // OK, no syntax error }Note that the previous err would be reassigned anyway, and in the last example the output is 1, 2, err2.
If you still need the previous error, either use a different variable name or, if inside a function where "collecting" errors makes sense, use errors.Join.
import ( "errors" "fmt" ) func err1() (int, error) { return 1, fmt.Errorf("err1") } func err2() (int, error) { return 2, fmt.Errorf("err2") } func main() { _, err1 := err1() _, err2 := err2() err := errors.Join(err1, err2) fmt.Println(err) }The outputs is
err1 err2