Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct initialization in if statements

I want to check if a struct is empty, i.e. if all of its fields are set to their default value. The following works as expected:

package main

import "fmt"

type MyStruct struct {
    field1 string
    field2 int
}

func main() {
    var mine MyStruct
    empty := MyStruct{}

    // Check if mine is empty.
    if mine == empty {
        fmt.Print("mine is empty")
    }
}

I wanted to shorten this a bit so I moved the empty struct initialization into the if statement:

func main() {
    var mine MyStruct

    // Check if mine is empty.
    if mine == MyStruct{} {
        fmt.Print("mine is empty")
    }
}

But that does not work: syntax error: unexpected }, expecting := or = or comma. Even the following does not work although it seems almost the same as the first example:

func main() {
    var mine MyStruct

    // Check if mine is empty.
    if empty := MyStruct{}; mine == empty {
        fmt.Print("mine is empty")
    }
}

The compiler says: syntax error: need trailing comma before newline in composite literal. I found the following code to work, however:

func main() {
    var mine MyStruct

    // Check if mine is empty.
    if mine == *new(MyStruct) {
        fmt.Print("mine is empty")
    }
}

Can someone explain why the two above examples are not accepted by the compiler? And while we're at it: What's the idiomatic way to check for an "empty" struct? The last example works but looks a bit odd to me.

like image 361
Oliver Avatar asked Aug 09 '14 19:08

Oliver


1 Answers

Resolve the {} ambiguity with parentheses. For example,

package main

import "fmt"

type MyStruct struct {
    field1 string
    field2 int
}

func main() {
    var mine MyStruct

    // Check if mine is empty.
    if mine == (MyStruct{}) {
        fmt.Print("mine is empty")
    }
}

The Go Programming Language Specification

Composite literals

A parsing ambiguity arises when a composite literal using the TypeName form of the LiteralType appears as an operand between the keyword and the opening brace of the block of an "if", "for", or "switch" statement, and the composite literal is not enclosed in parentheses, square brackets, or curly braces. In this rare case, the opening brace of the literal is erroneously parsed as the one introducing the block of statements. To resolve the ambiguity, the composite literal must appear within parentheses.

like image 194
peterSO Avatar answered Nov 14 '22 23:11

peterSO