Steve Brisk
Steve Brisk

Reputation: 2743

Why is struct creation in an if statement illegal in Go?

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)
}

Upvotes: 10

Views: 1320

Answers (1)

Gonzalo
Gonzalo

Reputation: 21175

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}

Upvotes: 19

Related Questions