英文:
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.Name
、temp.Email
、temp.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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论