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

检查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 
}
  • 写回答

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制