最新消息:yaf表单扩展中新增加了浮点数、日期和集合的校验。php yaf框架扩展实践三——表单

golang err is shadowed during return

Golang 1020浏览 0评论

先用代码模拟下这种错误:

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
}

转载请注明:快乐编程 » golang err is shadowed during return

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址