为什么if语句中的struct创建在Go中是非法的?

Ste*_*isk 10 go

Go抱怨在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)
    }
}
Run Code Online (Sandbox Code Playgroud)

错误(在if语句行上):语法错误:意外:,期待:=或=或逗号

这会产生相同的错误:

if auth2 := Auth {Username: "abc", Password: "123"}; auth == auth2 {
            fmt.Println(auth)
}
Run Code Online (Sandbox Code Playgroud)

这按预期工作:

auth2 := Auth {Username: "abc", Password: "123"};
if  auth == auth2 {
        fmt.Println(auth)
}
Run Code Online (Sandbox Code Playgroud)

Gon*_*alo 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}
Run Code Online (Sandbox Code Playgroud)

  • 为了完整起见:"当在关键字和"if","for"或"switch"语句的块的左括号之间出现使用LiteralType的TypeName形式的复合文字时,会出现解析歧义,因为围绕文字中表达式的大括号与引入语句块的大括号相混淆.为了解决这种罕见情况下的歧义,复合文字必须出现在括号内. - http://golang.org/ref/spec (8认同)