[轉]GO err is shadowed during return

1 前言函數

有時候編譯Go項目會出現GO err is shadowed during return的問題,是由於做用域致使變量重名,return時不是你預期的變量致使的。spa

2 樣例.net

這裏先復現問題,而後進行問題說明。blog

//test.go
package main


import "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,問題復現了,下面進行問題分析。string

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

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.編譯

下面進行修改(只須要保證局部變量和全局變量不重名便可):class

3 解決方案test

func foo(x string) (ret int, err error) {
	if true {
		ret1, err1 := strconv.Atoi(x)
		if err1 != nil {
			err = err1
			return
		}
		ret = ret1
	}

	return ret, nil
}

運行:

4 參考

轉載於:https://blog.csdn.net/wo198711203217/article/details/60574268 

相關文章
相關標籤/搜索