Refactor GetStructPointers
This commit is contained in:
parent
7977cf1721
commit
8298da6f48
1 changed files with 18 additions and 12 deletions
|
@ -122,27 +122,33 @@ func GetStructValues(obj interface{}, columns ...string) []interface{} {
|
||||||
// GetStructPointers returns a slice of pointers to the matching columns in obj
|
// GetStructPointers returns a slice of pointers to the matching columns in obj
|
||||||
func GetStructPointers(obj interface{}, columns ...string) []interface{} {
|
func GetStructPointers(obj interface{}, columns ...string) []interface{} {
|
||||||
val := reflect.ValueOf(obj).Elem()
|
val := reflect.ValueOf(obj).Elem()
|
||||||
var ret []interface{}
|
|
||||||
|
var ln int
|
||||||
|
var getField func(reflect.Value, int) reflect.Value
|
||||||
|
|
||||||
if len(columns) == 0 {
|
if len(columns) == 0 {
|
||||||
fieldsLen := val.NumField()
|
ln = val.NumField()
|
||||||
ret = make([]interface{}, fieldsLen)
|
getField = func(v reflect.Value, i int) reflect.Value {
|
||||||
for i := 0; i < fieldsLen; i++ {
|
return v.Field(i)
|
||||||
ret[i] = val.Field(i).Addr().Interface()
|
}
|
||||||
|
} else {
|
||||||
|
ln = len(columns)
|
||||||
|
getField = func(v reflect.Value, i int) reflect.Value {
|
||||||
|
return v.FieldByName(strmangle.TitleCase(columns[i]))
|
||||||
}
|
}
|
||||||
return ret
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ret = make([]interface{}, len(columns))
|
ret := make([]interface{}, ln)
|
||||||
|
for i := 0; i < ln; i++ {
|
||||||
|
field := getField(val, i)
|
||||||
|
|
||||||
for i, c := range columns {
|
|
||||||
field := val.FieldByName(strmangle.TitleCase(c))
|
|
||||||
if !field.IsValid() {
|
if !field.IsValid() {
|
||||||
panic(fmt.Sprintf("Could not find field on struct %T for field %s", obj, strmangle.TitleCase(c)))
|
// Although this breaks the abstraction of getField above - we know that v.Field(i) can't actually
|
||||||
|
// produce an Invalid value, so we make a hopefully safe assumption here.
|
||||||
|
panic(fmt.Sprintf("Could not find field on struct %T for field %s", obj, strmangle.TitleCase(columns[i])))
|
||||||
}
|
}
|
||||||
|
|
||||||
field = field.Addr()
|
ret[i] = field.Addr().Interface()
|
||||||
ret[i] = field.Interface()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return ret
|
return ret
|
||||||
|
|
Loading…
Reference in a new issue