duane2364
2016-10-18 11:40
浏览 161
已采纳

检查struct是否为空,如果struct包含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 
}

图片转代码服务由CSDN问答提供 功能建议

我正在尝试创建方法扩展,以检查我的结构是否已初始化,但出现此错误:

无效操作:myStruct文字== inStruct(无法比较包含json.RawMessage的结构)

这是我的代码:

 包数据模型
 
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 
} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dqt66847 2016-10-18 12:14
    已采纳

    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

    已采纳该答案
    打赏 评论
  • dpbvpgvrhwxen3222 2016-10-18 21:58

    The zero value of myStruct is a struct where a, b and c are zero values of their type. The zero value of a string is "", of json.RawMessage it is nil (because it's just an alias for []byte). Combining this knowledge you get:

    type myStruct struct {
        a string
        b json.RawMessage
        c json.RawMessage
    }
    
    func (m *myStruct ) IsEmpty() bool {
        return m.a == "" && m.b == nil && m.c == nil
    }
    

    There is no need for reflect.DeepEqual()

    打赏 评论

相关推荐 更多相似问题