简体   繁体   English

确认Go中的结构字段非零

[英]Confirm struct fields non-zero in Go

I am trying to write a generic function that takes a struct and confirms that the given fields have non-zero values. 我正在尝试编写一个采用struct并确认给定字段具有非零值的通用函数。

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 . 如果将struct作为i传入,则效果很好,但如果i是指向struct的指针,则失败。

How can I reflect on the value of an interface if the value passed in is a pointer? 如果传入的值是指针,如何反映接口的值?

You can use reflect.Indirect , which returns the value that v points to. 您可以使用reflect.Indirect ,它返回v指向的值。 If v is a nil pointer, Indirect returns a zero Value. 如果v是nil指针,则Indirect返回零值。 If v is not a pointer, Indirect returns v. 如果v不是指针,则Indirect返回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. 如果要检查该值是否是指针,请检查它的Kind ,然后使用Elem()取消引用该指针。

v := reflect.ValueOf(i)
if v.Kind() == reflect.Ptr {
    v = v.Elem()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM