vishes_shell
vishes_shell

Reputation: 23504

Check if any field of struct is nil

If there any clean way to check if any field value of struct is nil?

Suppose i have

type test_struct struct {
    Name    string `json:"name" binding:"required"`
    Email   string `json:"email" binding:"required"`
    Message string `json:"message" binding:"required"`
}

And with Gin i am filling the struct with values as

var temp test_struct
c.Bind(&temp)

And everything works fine, but i want to check if any of temp.Name, temp.Email, temp.Message is nil, sure we can check it by simply comparing each field with nil: if temp.Name == nil and so on, but i am looking for a cleaner version of that, is there any?

UPD: Due to a lack of knowledge in Go language i didn't know that the Bind function of gin package return an error if we pass a strucure with binding:"required" fields. Thanks to @matt.s i get it. So the answer would be to check the err:

var temp test_struct
err := c.Bind(&temp)
if err != nil {
    // Do my stuff(some of fields are not set)
}

Upvotes: 0

Views: 1160

Answers (1)

matt.s
matt.s

Reputation: 1736

You should first check that Bind doesn't return an error. If it doesn't then all fields will be set to their appropriate values or initialized to zero values if not. This means that the strings are guaranteed to not be nil (though they will be set to "" if they did not have a value).

Upvotes: 3

Related Questions