Golang的Semicolons

zolo · · 1134 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

Semicolons

The formal grammar uses semicolons ";" as terminators in a number of productions. Go programs may omit most of these semicolons using the following two rules:

  1. When the input is broken into tokens, a semicolon is automatically inserted into the token stream at the end of a non-blank line if the line's final token is

     

  2. To allow complex statements to occupy a single line, a semicolon may be omitted before a closing ")" or "}".

To reflect idiomatic use, code examples in this document elide semicolons using these rules.

说得很清楚:

Golang编译器自动在行尾插入分号(Semicolons):

    1. 关键字keywords

    2. 标识符identifiers

    3. 直接量Literals

    4. 某些运算符: ++, --, ), ], }

由于在初始化块{...}中使用逗号而不是分号, 所以在块内换行需要谨慎编译器会自动插入分号.

var files = []struct { Name, Body string }{ {"readme.txt", "This archive contains some text files."}, {"gopher.txt","Gopher names:\nGeorge\nGeoffrey\nGonzo"}, {"todo.txt", "Get animal handling license."}

}

编译时会报错, 原因是在最后一个元素后自动插入了分号, 解决办法:

    1. 在最后一个元素后也加逗号

var files = []struct { Name, Body string }{ {"readme.txt", "This archive contains some text files."}, {"gopher.txt","Gopher names:\nGeorge\nGeoffrey\nGonzo"}, {"todo.txt", "Get animal handling license."},

}

    2. 最后"}"不换行

var files = []struct {

Name, Body string }{ {"readme.txt", "This archive contains some text files."}, {"gopher.txt", "Gophernames:\nGeorge\nGeoffrey\nGonzo"}, {"todo.txt", "Get animal handling license."}}


有疑问加站长微信联系(非本文作者)

本文来自:博客园

感谢作者:zolo

查看原文:Golang的Semicolons

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1134 次点击  
加入收藏 微博
下一篇:Golang与MySQL
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传