Golang: Conditional with Empty Struct

type User struct {
	id   int
	name string
}

This will generate an error

user1 := User{}

if user1 == User{} {
	fmt.Println("Empty struct")
}

The correct way to write is to enclose struct with parentheses (User{})

user1 := User{}

if user1 == (User{}) {
	fmt.Println("Empty struct")
}

However, this works

switch {
case user1 == User{}:
	fmt.Println("Empty struct")
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *