fields.go raw

   1  package generic
   2  
   3  import "reflect"
   4  
   5  // HasField returns true if given struct has a field with given name
   6  // Also allow a slice, it will use the underlying type
   7  func HasField(i any, fieldName string) bool {
   8  	value := reflect.Indirect(reflect.ValueOf(i))
   9  	typ := value.Type()
  10  
  11  	if value.Kind() == reflect.Slice {
  12  		typ = indirectType(typ.Elem())
  13  	}
  14  
  15  	_, fieldExists := typ.FieldByName(fieldName)
  16  	return fieldExists
  17  }
  18