Skip to content

Instantly share code, notes, and snippets.

@NatGra
Created May 20, 2021 09:54
Show Gist options
  • Save NatGra/1972d860e1f4b7d2216813514431b1d9 to your computer and use it in GitHub Desktop.
Save NatGra/1972d860e1f4b7d2216813514431b1d9 to your computer and use it in GitHub Desktop.
GoLang - Check if a (custom) struct is empty
// Learing GoLang - Check if a (custom) struct is empty
//
// Possible data type
// {
// "type": "music",
// "duration": 200,
// "musicData": {
// "title": "Sinfonie op. 2 Nr.4 F-dur 3.Satz Gavot Allegro",
// "album": null,
// "artist": "William Boyce",
// "images": []
// },
// "nonMusicData": null
// }
//
// {
// "type": "talk",
// "duration": 500,
// "musicData": null
// "nonMusicData": {
// "title": "BBC World Service",
// "program": null,
// "images": []
// },
// }
//
// Try it out: https://play.golang.org/p/25-uw73l5ug
package main
import (
"fmt"
"reflect"
)
type (
ResponseData struct {
Type string `json:"type"`
MusicData MusicDataType `json:"musicData"`
NonMusicData NonMusicDataType `json:"nonMusicData"`
}
MusicDataType struct {
Title string `json:"title"`
Album string `json:"album"`
Artist string `json:"artist"`
Images []ImageType `json:"images"`
}
NonMusicDataType struct {
Title string `json:"title"`
Program string `json:"program"`
Images []ImageType `json:"images"`
}
ImageType struct {
Url string `json:"url"`
}
)
func checkObjects(data ResponseData) {
if (reflect.DeepEqual(data.MusicData, MusicDataType{})) {
fmt.Println("MusicData is empty")
} else {
fmt.Println("MusicData is not empty")
}
if (reflect.DeepEqual(data.NonMusicData, NonMusicDataType{})) {
fmt.Println("NonMusicData is empty")
} else {
fmt.Println("NonMusicData is not empty")
}
}
func main() {
checkObjects(ResponseData{
MusicData: MusicDataType{
Title: "Sinfonie op. 2 Nr.4 F-dur 3.Satz Gavot Allegro",
},
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment