doutuan9357 2016-04-23 08:09 采纳率: 100%
浏览 77
已采纳

检查struct的任何字段是否为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条回答 默认 最新

  • dqj96395 2016-04-23 09:14
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64