這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
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, or return
- 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."}}