【问题标题】:Check empty struct that have array fields检查具有数组字段的空结构
【发布时间】:2017-08-16 05:49:03
【问题描述】:

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

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

请注意,不能使用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"`
}

【问题讨论】:

  • 迭代是唯一的可能。

标签: arrays go struct slice


【解决方案1】:

这些是slices,而不是arrays。重要的是要强调,因为数组是可比较的,但切片不是。见Spec: Comparision operators。而且由于切片不可比较,由它们组成的结构(具有切片类型的字段的结构)也不可比较。

您可以为此使用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

【讨论】:

  • 我使用了来自 github 的一个名为 deep 或 Deep 的包,它有一个类似于 reflect.DeepEqual() 的方法,它也识别了第一个不相等的组件。
猜你喜欢
  • 1970-01-01
  • 2017-10-11
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 2014-09-05
相关资源
最近更新 更多