Golang的Semicolons
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:
-
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
- an identifier
- an integer, floating-point, imaginary, rune, or string literal
- one of the keywords
break
,continue
,fallthrough
, orreturn
- one of the operators and delimiters
++
,--
,)
,]
, or}
- 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."}}
· 为什么 .NET8线程池 容易引发线程饥饿
· golang自带的死锁检测并非银弹
· 如何做好软件架构师
· 记录一次线上服务OOM排查
· Linux实时系统Xenomai宕机问题的深度定位过程
· 2025年广告第一单,试试这款永久免费的开源BI工具
· o3 发布了,摔碎了码农的饭碗
· SQL优化的这15招,真香!
· [.NET] API网关选择:YARP还是Ocelot?
· 将 EasySQLite 从 .NET 8 升级到 .NET 9