为什么在Go语言中,在if语句中创建结构体是非法的?

huangapple go评论88阅读模式
英文:

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}

huangapple
  • 本文由 发表于 2013年4月3日 04:42:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/15773969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定