英文:
What is the problem of Go in this context syntactically?
问题
我试图编写一个函数,但这里的问题让我感到惊讶。
userGroup.Use(
middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
if username == "joe" && password == "123"{
return true, nil
}
return false, nil
}) // <- 错误发生在这里
)
userGroup.Use(
middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
if username == "joe" && password == "123"{
return true, nil
}
return false, nil
})) // <- !!
花了一个小时来查找错误,结果发现最后一个闭合括号不能漂浮在外面。**这是分号、逗号还是缩进的问题?**我记得 JavaScript 对这种东西不太在意。
我得到的错误是:
missing ',' before newline in argument list |syntax
英文:
I was trying to write a function but the issue here surprised me.
userGroup.Use(
middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
if username == "joe" && password == "123"{
return true, nil
}
return false, nil
}) // <- error happens here
)
userGroup.Use(
middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
if username == "joe" && password == "123"{
return true, nil
}
return false, nil
})) // <- !!
Spent an hour for a bug but turns out the last closing parentheses must not float around. Is this an issue with semicolons, commas or indentation?
I remember JS not caring about this kind of stuff
The error I was getting was :
missing ',' before newline in argument list |syntax
答案1
得分: 2
这是 Golang 的分号规则的结果:https://go.dev/doc/effective_go#semicolons,Go 在扫描源代码时会添加分号,所以原始源代码中没有分号。
根据规则“如果换行符出现在可能结束语句的标记之后,则插入分号”,你之前的代码将如下所示:
userGroup.Use(
middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
if username == "joe" && password == "123"{
return true, nil
}
return false, nil
}); // <- 在这里添加了分号
)
这当然是错误的,会导致错误。将该行的闭括号移动到分号之前可以修复这个问题。
英文:
This is the result of Golang's semi-colon rule: https://go.dev/doc/effective_go#semicolons, where Go is adding a semicolon as it scans the source, so the original source is free of semicolon.
Following the rule "if the newline comes after a token that could end a statement, insert a semicolon", your earlier code would look like below:
userGroup.Use(
middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
if username == "joe" && password == "123"{
return true, nil
}
return false, nil
}); // <- semicolon added here
)
which of course wrong and causes an error. Moving the closing parentheses on that line instead fixes that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论