为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕桂英546537 2019-02-05 14:10:42
失败的原因在于,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
}



查看完整回答
反对 回复 2019-03-16
?
倚天杖

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完了之后状态不会再有改变,不会有其他情况发生的时候,else应该被省略。

所以去掉else吧,因为编译器它看来你需要有一个default return。
改好之后是这样:

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


查看完整回答
反对 回复 2019-03-16
  • 3 回答
  • 0 关注
  • 932 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信