douzhigan1687 2012-07-23 06:28 采纳率: 0%
浏览 54
已采纳

如果/ for / func块的开括号位置必须在同一行上,该走吗?

Does a go block following a for, func or if statement have to have the opening brace on the same line? I get a compile error if I move it down but I can't see in the language spec where they show that a block has to be structured like that.

A block is a sequence of declarations and statements within matching brace brackets.

Block = "{" { Statement ";" } "}" .

IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .

  • 写回答

1条回答 默认 最新

  • dongqie2355 2012-07-23 06:56
    关注

    From Effective Go, because of semicolon inference:

    One caveat.
    You should never put the opening brace of a control structure (if, for, switch, or select) on the next line.
    If you do, a semicolon will be inserted before the brace, which could cause unwanted effects. Write them like this:

    if i < f() {
        g()
    }
    

    not like this:

    if i < f()  // wrong!
    {           // wrong!
        g()
    }
    

    As jnml comments, the language syntax is correct for blocks.
    But combined with Semicolon injection, it means you should really:

    • always put the brace on the same line than the if statement (or the 'if' won't do what you think it should)
    • actually, always use gofmt and don't think about it (Preferably, gofmt your code each time you save it in your editor. It is fast and will make your code consistent with the rest of any Go code out there)

    Even the Go compiler will enforce that "same line for brace" rule, to avoid any unforeseen side-effect.
    So the language reference doesn't say where to put the brace, but both gofmt and the compiler will make sure it is correctly placed for a if statement.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)