DiagnosticsError codes
M0028 shadowed variable
A := in an inner block declares a new variable with the same name as one in an outer block.
example $ marmot build . error[M0028]: declared and not used: err --> ./main.go:10:9 | 8 | var err error | --- the outer `err` is declared here and is not assigned ... 10 | data, err := load() | ^^^ this `err` is a new variable that shadows the outer one | = help: to assign the outer `err`, declare the other variables before the statement and use `=` instead of `:=` error: build failed with 1 error for more about an error, run `marmot explain M0028`
The program that produced it
package main
import "os"
func load() ([]byte, error) { return os.ReadFile("config.json") }
func run(ok bool) error {
var err error
if ok {
data, err := load()
_ = data
}
return err
}
func main() { _ = run(true) }
Assignments go to the inner one, which is then unused, and the outer one keeps its old value. This often loses an error.
The mistake and the fix
var err error
if ok {
data, err := load() // a new err
use(data)
}
return err // always nilvar err error
if ok {
var data []byte
data, err = load()
use(data)
}
return err The fix
Declare the other variables first and assign with =.
See also all error codes and marmot explain.