這里先復現問題,然后進行問題說明。
//test.go
package mainimport "fmt"import "strconv"func foo(x string) (ret int, err error) { if true { ret, err := strconv.Atoi(x) if err != nil { return } } return ret, nil}func main() { fmt.PRintln(foo("123"))}運行:

OK,問題復現了,下面進行問題分析。
func foo(x string) (ret int, err error) {//返回值列表定義了ret和err變量,作用域是整個函數體if true {//新的語句塊ret, err := strconv.Atoi(x) //這里又定義了新的變量ret和err,和返回值列表重名了。作用域是if語句塊if err != nil {return //這里的return語句會導致外層的ret和err被返回,而不是if語句里的ret和err}}return ret, nil}
來自網上的解釋:
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.下面進行修改(只需要保證局部變量和全局變量不重名即可)://test.go
package mainimport "fmt"import "strconv"func foo(x string) (ret int, err error) {if true {ret1, err1 := strconv.Atoi(x)if err1 != nil {err = err1return}ret = ret1}return ret, nil}func main() {fmt.Println(foo("123"))}
運行:

新聞熱點
疑難解答