繼續(xù)來控go語言的陷阱焕议,今天來一發(fā)go語言中未使用變量的陷阱贾陷,不使用就扔掉嘛逮京,go語言發(fā)明人如是說...
先來看坑:
package main
var gvar int //not an error
func main() {
var one int //error, unused variable
two := 2 //error, unused variable
var three int //error, even though it's assigned 3 on the next line
three = 3
}
運(yùn)行結(jié)果
./hello.go:6: one declared and not used
./hello.go:7: two declared and not used
./hello.go:8: three declared and not used
好吧,one卿堂、two、three這三個(gè)變量都有問題懒棉。one只是作了聲明草描,two賦值,three先聲明后賦值策严,本質(zhì)上這三個(gè)變量都沒有被使用穗慕。
來看正確的寫法:
package main
import "fmt"
package main
import "fmt"
func main() {
var one int
_ = one
fmt.Println(one)
two := 2
fmt.Println(two)
var three int
three = 3
one = three
var four int
four = four
}
運(yùn)行結(jié)果
0
2
對于未賦值的整型變量one,go默認(rèn)賦值為0。由正確的寫法可以看出妻导,在go中揍诽,對于使用的定義,是變量需要出現(xiàn)在賦值號的右邊栗竖,變量才被認(rèn)為使用了。go的這種設(shè)計(jì)很合理渠啤,運(yùn)行程序的過程中狐肢,減少了一些不必要的判斷與賦值,相對一python而言沥曹,容錯(cuò)性變差份名,僅這一點(diǎn)而言,性能會更好妓美。