Search code examples
gostructequality

Check if struct is empty if struct contains json.RawMessage


I'm trying to create a method extension to check if my struct was initialized but I'm getting this error:

invalid operation: myStruct literal == inStruct (struct containing json.RawMessage cannot be compared)

Here's my code:

package datamodels

import "encoding/json"

type myStruct struct {
        a string json:"a"
        b json.RawMessage json:"b"
        c json.RawMessage json:"c"
    }

func (m *myStruct ) IsEmpty() bool {
    return (myStruct {}) == m 
}

Solution

  • The reason is that json.RawMessage is a Alias for a []byte and maps, slices etc can not be compared normally.

    You can compare slices with reflect.DeepEqual method.

    See example below.

    package main
    
    import "encoding/json"
    import "reflect"
    
    type myStruct struct 
    {
            a string `json:"a"`
            b json.RawMessage `json:"b"`
            c json.RawMessage `json:"c"`
    }   
    
    func (m myStruct ) IsEmpty() bool {
        return reflect.DeepEqual(myStruct{}, m)
    }
    
    
    func main() {
        var mystuff myStruct = myStruct{}
    
        mystuff.IsEmpty()
    }
    

    GOLANG Playground

    Reference for comparing slices: How to compare struct, slice, map are equal?

    See the RawMessage type. json.RawMessage type: https://golang.org/src/encoding/json/stream.go?s=6218:6240#L237