英文:
Why is struct creation in an if statement illegal in Go?
问题
Go抱怨在if语句中实例化一个结构体。为什么?有没有不涉及临时变量或新函数的正确语法?
type Auth struct {
Username string
Password string
}
func main() {
auth := Auth { Username : "abc", Password : "123" }
if auth == Auth {Username: "abc", Password: "123"} {
fmt.Println(auth)
}
}
错误(在if语句行上):语法错误:意外的“:”,期望“:=”或“=”或逗号
这会产生相同的错误:
if auth2 := Auth {Username: "abc", Password: "123"}; auth == auth2 {
fmt.Println(auth)
}
这样可以正常工作:
auth2 := Auth {Username: "abc", Password: "123"};
if auth == auth2 {
fmt.Println(auth)
}
英文:
Go complains about instantiating a struct in an if-statement. Why? Is there correct syntax for this that doesn't involve temporary variables or new functions?
type Auth struct {
Username string
Password string
}
func main() {
auth := Auth { Username : "abc", Password : "123" }
if auth == Auth {Username: "abc", Password: "123"} {
fmt.Println(auth)
}
}
Error (on the if-statement line): syntax error: unexpected :, expecting := or = or comma
This yields the same error:
if auth2 := Auth {Username: "abc", Password: "123"}; auth == auth2 {
fmt.Println(auth)
}
This works as expected:
auth2 := Auth {Username: "abc", Password: "123"};
if auth == auth2 {
fmt.Println(auth)
}
答案1
得分: 20
你必须在==的右边加上括号。否则,Go语言会认为'{'是'if'块的开始。以下代码可以正常工作:
package main
import "fmt"
type Auth struct {
Username string
Password string
}
func main() {
auth := Auth { Username : "abc", Password : "123" }
if auth == (Auth {Username: "abc", Password: "123"}) {
fmt.Println(auth)
}
}
// 输出:{abc 123}
英文:
You have to surround the right side of the == with parenthesis. Otherwise go will think that the '{' is the beginning of the 'if' block. The following code works fine:
package main
import "fmt"
type Auth struct {
Username string
Password string
}
func main() {
auth := Auth { Username : "abc", Password : "123" }
if auth == (Auth {Username: "abc", Password: "123"}) {
fmt.Println(auth)
}
}
// Output: {abc 123}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论