github.com/keysonZZZ/kmg@v0.0.0-20151121023212-05317bfd7d39/typeTransform/SliceStructToMapStruct.go (about)

     1  package typeTransform
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  )
     7  
     8  //transform slice of struct to map of struct,
     9  //it will report error if Id is not unique
    10  //有Id重复验证
    11  func SliceStructToMapStruct(in interface{}, out interface{}, idFieldName string) (err error) {
    12  	inV := reflect.ValueOf(in)
    13  	outV := reflect.ValueOf(out)
    14  	if inV.Kind() == reflect.Ptr {
    15  		inV = inV.Elem()
    16  	}
    17  	if outV.Kind() == reflect.Ptr {
    18  		outV = outV.Elem()
    19  	}
    20  	return sliceStructToMapStructValue(inV, outV, idFieldName)
    21  }
    22  func sliceStructToMapStructValue(in reflect.Value, out reflect.Value, idFieldName string) (err error) {
    23  	out.Set(reflect.MakeMap(out.Type()))
    24  	len := in.Len()
    25  	isOutPtr := out.Type().Elem().Kind() == reflect.Ptr
    26  	for i := 0; i < len; i++ {
    27  		thisValue := in.Index(i)
    28  		oKey := thisValue.FieldByName(idFieldName)
    29  		if !oKey.IsValid() {
    30  			return fmt.Errorf(`id field name "%s" not exist in "%s"`, idFieldName, thisValue.Type().Name())
    31  		}
    32  		if isOutPtr {
    33  			thisValue = thisValue.Addr()
    34  		}
    35  		oExist := out.MapIndex(oKey)
    36  		if oExist.IsValid() {
    37  			return fmt.Errorf(`%s:%v repeat`, idFieldName, oKey.Interface())
    38  		}
    39  		out.SetMapIndex(oKey, thisValue)
    40  	}
    41  	return
    42  }