2

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
  • Iteration is the only possibility. Commented Aug 16, 2017 at 8:27

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

I have used a package from github called deep or Deep which has a method similar to reflect.DeepEqual(), which also identifies the first non-equal component.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.