Menu Close

Go – how to check if structure is empty in go golang ?

In this article, We will be triaging about empty structure in go golang. We will also verify using programs whether structure is empty or not.

The size of empty structure is zero in golang. If there are none fields in the structure. Then It is a empty structure.

Syntax:

Type structure_name struct {

}

Example: 1

package main

import (
    "fmt"
)

type Vehicle struct {

}

func main() {

    var st Vehicle

    if (Vehicle{} == st) {

        fmt.Println("It is empty structure")

    } else {

        fmt.Println("It is not empty structure")

    }
}

Output:

It is empty structure

  

Example: 2

package main

import (
    "fmt"
)

type Vehicle struct {

    size int

}

func main() {

    var st Vehicle

    if (Vehicle{20} == st) {

        fmt.Println("It is empty structure")

    } else {

        fmt.Println("It is not empty structure")

    }
}

Output:

It is not empty structure
 If there is at least one field in the structure. Then given below sample code to test whether structure field has been initialised or not. 

Syntax:

Type structure_name struct {

    variable_name type

}

Example: 1

package main

import (

    "fmt"
    "reflect"

)

type Vehicle struct {

    size int
}

func (x Vehicle) IsStructureEmpty() bool {

    return reflect.DeepEqual(x, Vehicle{})

}

func main() {

    vehicle := Vehicle{}

    if vehicle.IsStructureEmpty() {

        fmt.Println("It is empty structure")

    } else {

        fmt.Println("It is not empty structure")

    }
}

Output:

It is empty structure

Example: 2

package main

import (

    "fmt"
    "reflect"

)

type Vehicle struct {

    size int

}

func (x Vehicle) IsStructureEmpty() bool {

    return reflect.DeepEqual(x, Vehicle{})

}

func main() {

    vehicle := Vehicle{}

    vehicle.size = 20

    if vehicle.IsStructureEmpty() {

        fmt.Println("It is empty structure")

    } else {

        fmt.Println("It is not empty structure")

    }
}
It is not empty structure

Using switch statement :

Example: 1

package main

import (

    "fmt"

)

type Vehicle struct {

}

func main() {

    vehicle := Vehicle{}

    switch {

        case vehicle == Vehicle{}:

            fmt.Println("Structure is empty")

        default:

            fmt.Println("Structure is not empty")
    }
}

O/p:

Structure is empty

Eg2:

package main

import (

    "fmt"

)

type Vehicle struct {

    size int

}

func main() {

    vehicle := Vehicle{}

    switch {

        case vehicle == Vehicle{20}:

            fmt.Println("Structure is empty")

        default:

            fmt.Println("Structure is not empty")
    }
}

Output:

Structure is not empty

References: https://tour.golang.org/moretypes/2

To learn more about golang, Please follow given below link:
https://www.techieindoor.com/go-lang/

Posted in golang, Miscellaneous

Leave a Reply

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