The following code generates the compile error : \"err declared and not used\". If there is a scope/shadowing issue here, it\'s due to a principle I don\'t understand. Can s
This is not because of any shadowing. You have not used err
variable that is declared for anything but assigning a value to it .
according to FAQ
The presence of an unused variable may indicate a bug, while unused imports just slow down compilation. Accumulate enough unused imports in your code tree and things can get very slow. For these reasons, Go allows neither
If you declare a variable it has to be used
In the given program err
is declared and is being used to assign data to .The value of err
is not used at all
You may bipass this kind of error by doing a _ assignment
ie,
var _ = err
or
using err
like
if err != nil {
fmt.Println(err.Error())
return
}
The following code would solve it,but i would suggest use the err for checking error
package main
import (
"fmt"
)
func main() {
var (
err error
dto = make(map[string]interface{})
)
_ = err
dto[`thing`], err = getThings()
fmt.Println(dto[`thing`])
}
func getThings() (string, error) {
return `the thing`, nil
}
PS : You must use variables you declare inside functions, but it's OK if you have unused global variables. It's also OK to have unused function arguments.