dsfd3546 2017-02-03 14:09
浏览 28
已采纳

确认Go中的结构字段非零

I am trying to write a generic function that takes a struct and confirms that the given fields have non-zero values.

This is my function:

func CheckRequiredFields(kind string, i interface{}, fields ...string) error {
    for _, field := range fields {
        value := reflect.ValueOf(i).FieldByName(field)
        if value.Interface() == reflect.Zero(value.Type()).Interface() {
            return fmt.Errorf("missing required %s field %s", kind, field)
        }
    }
    return nil
}

and it works well if a struct is passed in as i, but fails if i is a pointer to a struct.

How can I reflect on the value of an interface if the value passed in is a pointer?

  • 写回答

1条回答 默认 最新

  • dtpxi88884 2017-02-03 14:17
    关注

    You can use reflect.Indirect, which returns the value that v points to. If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v.

    If you want to check if the value was a pointer or not, check it's Kind, and use Elem() to dereference the pointer.

    v := reflect.ValueOf(i)
    if v.Kind() == reflect.Ptr {
        v = v.Elem()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 不同模型怎么用同一个shader
  • ¥15 安卓启动没有ais proxy与v4l2的log打印
  • ¥15 go怎么读取mdb文件里面的数据
  • ¥60 Matlab联合CRUISE仿真编译dll文件报错
  • ¥15 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?