go build
→
"undefined: <variable name>"
This error is caused when a variable isn’t defined before attempting to assign it a value. This can commonly happen when you forget to use the short declaration form’s colon (:
), or when you previously defined a variable and then later removed that declaration. For instance, imagine you had this code:
err := doStuff()
if err != nil {
// handle the err
}
err = doMoreStuff()
if err != nil {
// handle the err
}
And you later updated the code to remove the call to doStuff()
:
err = doMoreStuff()
if err != nil {
// handle the err
}
Because you no longer declare the variable before calling doMoreStuff()
you now need to update your code to declare the err
variable.
To fix this error you need to declare the undefined variable. Often you can do this by adding a :
to the very first declaration of it:
err := doMoreStuff()
if err != nil {
// handle the err
}
Or by adding a var err error
before the first usage of the variable:
err := doMoreStuff()
if err != nil {
// handle the err
}
Created by Jon Calhoun, but you can check out the source and contribute on GitHub