检查结构体的任何字段是否为nil。

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

Check if any field of struct is nil

问题

有没有一种简洁的方法来检查struct的任何字段值是否为nil

假设我有以下代码:

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

使用Gin框架,我将使用以下代码将值填充到struct中:

var temp test_struct
c.Bind(&temp)

一切都正常工作,但我想检查temp.Nametemp.Emailtemp.Message中的任何一个是否为nil。当然,我们可以通过将每个字段与nil进行简单比较来检查:if temp.Name == nil,依此类推,但我正在寻找更简洁的版本,是否有这样的方法?

更新:由于对Go语言的了解不足,我不知道gin包的Bind函数在传递具有binding:"required"字段的结构时会返回错误。感谢 @matt.s 的指导。因此,答案是检查err

var temp test_struct
err := c.Bind(&temp)
if err != 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)
}

答案1

得分: 3

你应该首先检查Bind是否返回错误。如果没有错误,那么所有字段将被设置为其适当的值,或者如果没有值,则初始化为零值。这意味着字符串保证不是nil(尽管如果它们没有值,它们将被设置为“”)。

英文:

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).

huangapple
  • 本文由 发表于 2016年4月23日 16:09:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/36808307.html
匿名

发表评论

匿名网友

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

确定