失敗的原因在于,Go編譯器無法找到終止該函數的 return 語句。編譯失敗的案例如下:func example(x int) int { if x == 0 { return 5
} else { return x
}
}
3 回答

翻閱古今
TA貢獻1780條經驗 獲得超5個贊
golang 1.4 版本的bug,最新1.7,更新吧。
1.4 可以寫成:
func example(x int) int { if x == 0 { return 5 } return x }

倚天杖
TA貢獻1828條經驗 獲得超3個贊
Effective Go里說了:
In the Go libraries, you'll find that when an if statement doesn't flow into the next statement—that is, the body ends in break, continue, goto, or return—the unnecessary else is omitted.
f, err := os.Open(name, os.O_RDONLY, 0) if err!=nil { return err } codeUsing(f)
也就是說當你if完了之后狀態(tài)不會再有改變,不會有其他情況發(fā)生的時候,else應該被省略。
所以去掉else吧,因為編譯器它看來你需要有一個default return。
改好之后是這樣:
func example(x int) int { if x == 0 { return 5 } return x }
- 3 回答
- 0 關注
- 1003 瀏覽
添加回答
舉報
0/150
提交
取消