来自 Python,我不习惯看到超过 80 列的代码行。 所以当我遇到这个时:
err := database.QueryRow("select * from users where user_id=?", id).Scan(&ReadUser.ID, &ReadUser.Name, &ReadUser.First, &ReadUser.Last, &ReadUser.Email)
我试图打破它
err := database.QueryRow("select * from users where user_id=?", id) \
.Scan(&ReadUser.ID, &ReadUser.Name, &ReadUser.First, &ReadUser.Last, &ReadUser.Email)
但我明白了
syntax error: unexpected \
我还尝试通过按 Enter 来打破行并在末尾添加一个分号:
err := database.QueryRow("select * from users where user_id=?", id)
.Scan(&ReadUser.ID, &ReadUser.Name, &ReadUser.First, &ReadUser.Last, &ReadUser.Email);
但我又得到了:
syntax error: unexpected .
所以我想知道 golangic 的方法是什么?
最佳答案
首先是一些背景。 Go 的形式语法使用分号 ";"
在许多产品中作为终止符,但 Go 程序可能会省略其中的大部分(并且它们应该有一个更清晰、易于阅读的源代码;gofmt
还删除了不必要的分号)。
规范列出了确切的规则。 Spec: 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 immediately after a line's final token if that 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 "}".
如您所见,是否在括号后插入换行符 )
, 一个分号 ;
将自动插入,因此下一行不会被视为上一行的延续。这就是您的情况发生的情况,因此下一行以 .Scan(&ReadUser.ID,...
开头会给你一个编译时错误,因为本身(没有前一行)是一个编译时错误:syntax error: unexpected .
因此,您可以在不与 1.
中列出的规则相冲突的任何地方断线。以上。
通常可以在逗号 ,
后换行, 在 opening 括号之后,例如(
, [
, {
, 在一个点 .
之后这可能是引用某个值的字段或方法。您还可以在二元运算符(需要 2 个操作数的运算符)之后换行,例如:
i := 1 +
2
fmt.Println(i) // Prints 3
这里值得注意的一点是,如果您有一个列出初始值的结构体、 slice 或映射文字,并且您想在列出最后一个值后换行,则必须放置一个强制性逗号 ,
即使这是最后一个值,也不会再出现,例如:
s := []int {
1, 2, 3,
4, 5, 6, // Note it ends with a comma
}
这是为了符合分号规则,也是为了让您可以重新排列和添加新行,而不必注意添加/删除最后的逗号;例如您可以简单地交换 2 行,而无需删除并添加新的逗号:
s := []int {
4, 5, 6,
1, 2, 3,
}
列出函数调用的参数时也是如此:
fmt.Println("first",
"second",
"third", // Note it ends with a comma
)
关于go - Golang如何破解一长串代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34846848/