简体   繁体   中英

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.

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?

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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