golang的这个正确的写法是什么?

失败的原因在于,Go编译器无法找到终止该函数的 return 语句。编译失败的案例如下:

func example(x int) int {    if x == 0 {        return 5
    } else {        return x
    }
}


慕桂英546537
浏览 937回答 3
3回答

翻阅古今

golang 1.4 版本的bug,最新1.7,更新吧。1.4 可以写成:func example(x int) int {    if x == 0 {        return 5     }      return x }

倚天杖

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完了之后状态不会再有改变,不会有其他情况发生的时候,else应该被省略。所以去掉else吧,因为编译器它看来你需要有一个default return。改好之后是这样:func example(x int) int {    if x == 0 {        return 5     }    return x }
打开App,查看更多内容
随时随地看视频慕课网APP