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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里