2018-07-03 17:47:23 +00:00
|
|
|
package reflect2
|
|
|
|
|
|
|
|
import "reflect"
|
|
|
|
|
|
|
|
// TagIndex returns a map that associates tag values with field indices.
|
|
|
|
func TagIndex(typ reflect.Type, tag string) map[string]int {
|
|
|
|
tagIndex := map[string]int{}
|
|
|
|
for i := 0; i < typ.NumField(); i++ {
|
|
|
|
tag := typ.Field(i).Tag.Get(tag)
|
|
|
|
if tag != "" {
|
|
|
|
tagIndex[tag] = i
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return tagIndex
|
|
|
|
}
|
|
|
|
|
|
|
|
// AssociateColumns returns a map that associates column indices with fields.
|
|
|
|
func AssociateColumns(typ reflect.Type, tag string, cols []string) map[int]int {
|
|
|
|
tagIndex := TagIndex(typ, tag)
|
|
|
|
colFields := map[int]int{}
|
|
|
|
for i, col := range cols {
|
|
|
|
if fi, ok := tagIndex[col]; ok {
|
|
|
|
colFields[i] = fi
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return colFields
|
|
|
|
}
|
2018-07-08 22:46:43 +00:00
|
|
|
|
|
|
|
// Dereference keeps dereferencing pointers until a value is found.
|
|
|
|
func Dereference(val reflect.Value) reflect.Value {
|
|
|
|
for val.Kind() == reflect.Ptr && val.CanAddr() {
|
|
|
|
val = val.Elem()
|
|
|
|
}
|
|
|
|
return val
|
|
|
|
}
|