先用代码模拟下这种错误:
package main import ( "strconv" ) func main() { foo("100") } func foo(i string) (err error) { count := 0 if count == 0 { _, err := strconv.ParseInt(i, 10, 64) if err != nil { return } } return }
这种代码从逻辑上来看,应当是没有问题的,但是不知道为什么运行后会报错:
$ go run shadowed.go # command-line-arguments buildin/shadowed.go:18: err is shadowed during return
从golang nuts上的答案来看,应当是作用域(scope)的问题:
It's a new scope, so a naked return returns the outer err, not your inner err that was != nil. So it's almost certainly not what you meant, hence the error.
参考地址:https://groups.google.com/forum/#!topic/golang-nuts/HmmZXC7KcVw
但是还是没有特别清楚具体的原因。解决办法就是声明另外一个err1变量来替代err变量:
package main import ( "strconv" ) func main() { foo("100") } func foo(i string) (err error) { count := 0 if count == 0 { _, err1 := strconv.ParseInt(i, 10, 64) if err1 != nil { err = err1 return } } return }