抱怨在if语句中实例化一个struct。为什么?是否有正确的语法,不涉及临时变量或新函数?
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)
}
答案 0 :(得分:19)
您必须用括号括起==的右侧。否则,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)
}
}
// Output: {abc 123}