如果结构包含 json.RawMessage,则检查结构是否为空
Check if struct is empty if struct contains json.RawMessage
我正在尝试创建一个方法扩展来检查我的结构是否已初始化,但我收到此错误:
invalid operation: myStruct literal == inStruct (struct containing json.RawMessage cannot be compared)
这是我的代码:
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
}
原因是json.RawMessage
是[]byte
的别名,地图、切片等不能正常比较。
您可以使用 reflect.DeepEqual
方法比较切片。
请参阅下面的示例。
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()
}
比较切片参考:How to compare struct, slice, map are equal?
参见RawMessage
类型。
json.RawMessage 类型:https://golang.org/src/encoding/json/stream.go?s=6218:6240#L237
myStruct
的零值是一个结构,其中 a
、b
和 c
是它们类型的零值。字符串的零值是 ""
,json.RawMessage
的零值是 nil
(因为它只是 []byte
的别名)。结合这些知识你会得到:
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
}
不需要reflect.DeepEqual()
我正在尝试创建一个方法扩展来检查我的结构是否已初始化,但我收到此错误:
invalid operation: myStruct literal == inStruct (struct containing json.RawMessage cannot be compared)
这是我的代码:
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
}
原因是json.RawMessage
是[]byte
的别名,地图、切片等不能正常比较。
您可以使用 reflect.DeepEqual
方法比较切片。
请参阅下面的示例。
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()
}
比较切片参考:How to compare struct, slice, map are equal?
参见RawMessage
类型。
json.RawMessage 类型:https://golang.org/src/encoding/json/stream.go?s=6218:6240#L237
myStruct
的零值是一个结构,其中 a
、b
和 c
是它们类型的零值。字符串的零值是 ""
,json.RawMessage
的零值是 nil
(因为它只是 []byte
的别名)。结合这些知识你会得到:
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
}
不需要reflect.DeepEqual()