检查具有数组字段的空结构体。

huangapple go评论146阅读模式
英文:

Check empty struct that have array fields

问题

我有一个嵌套的(非嵌入式)结构体,其中一些字段类型是数组。

如何检查此结构体的实例是否为空?(不使用迭代!)

请注意,不能使用StructIns == (Struct{})或空实例来进行比较!这段代码会出现以下错误:

invalid operation: user == model.User literal (struct containing model.Configs cannot be compared)

user.Configs.TspConfigs:

type TspConfigs struct {
	Flights		[]Flights	`form:"flights" json:"flights"`
	Tours		[]Tours		`form:"tours" json:"tours"`
	Insurances	[]Insurances`form:"insurances" json:"insurances"`
	Hotels		[]Hotels	`form:"hotels" json:"hotels"`
}
英文:

I have a nested (not embedded) struct for which some of field types are arrays.

How can I check if an instance of this struct is empty? (not using iteration!!)

Note that there can't use StructIns == (Struct{}) or by an empty instance! This code have this error:

invalid operation: user == model.User literal (struct containing model.Configs cannot be compared)

user.Configs.TspConfigs:

type TspConfigs struct {
	Flights		[]Flights	`form:"flights" json:"flights"`
	Tours		[]Tours		`form:"tours" json:"tours"`
	Insurances	[]Insurances`form:"insurances" json:"insurances"`
	Hotels		[]Hotels	`form:"hotels" json:"hotels"`
}

答案1

得分: 3

这些是切片(slices),而不是数组(arrays)。强调一下,数组是可比较的,但切片不是。请参考《规范:比较运算符》。由于切片不可比较,由它们组成的结构体(具有切片类型字段的结构体)也不可比较。

你可以使用reflect.DeepEqual()来进行比较。例如:

type Foo struct {
	A []int
	B []string
}

f := Foo{}
fmt.Println("Zero:", reflect.DeepEqual(f, Foo{}))
f.A = []int{1}
fmt.Println("Zero:", reflect.DeepEqual(f, Foo{}))

输出结果(在Go Playground上尝试):

Zero: true
Zero: false
英文:

Those are slices, not arrays. It's important to emphasize as arrays are comparable but slices are not. See Spec: Comparision operators. And since slices are not comparable, structs composed of them (structs with fields having slice types) are also not comparable.

You may use reflect.DeepEqual() for this. Example:

type Foo struct {
	A []int
	B []string
}

f := Foo{}
fmt.Println("Zero:", reflect.DeepEqual(f, Foo{}))
f.A = []int{1}
fmt.Println("Zero:", reflect.DeepEqual(f, Foo{}))

Output (try it on the Go Playground):

Zero: true
Zero: false

huangapple
  • 本文由 发表于 2017年8月16日 13:49:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/45705921.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定