github.com/keysonZZZ/kmg@v0.0.0-20151121023212-05317bfd7d39/typeTransform/StructFieldCopy.go (about) 1 package typeTransform 2 3 import ( 4 "reflect" 5 ) 6 7 // copy fields value between two pointer of struct, 8 // it will copy value with same field name in two struct 9 // it ignore not share field name 10 // it ignore share field name with not same type 11 // it ignore field can not set (it is addressable and was not obtained by the use of unexported struct fields) 12 func StructFieldCopy(in interface{}, out interface{}) { 13 vin := reflect.Indirect(reflect.ValueOf(in)) 14 tin := vin.Type() 15 vout := reflect.Indirect(reflect.ValueOf(out)) 16 tout := vout.Type() 17 if !vout.CanSet() { 18 panic("[StructFieldCopy] out can not set,you have to passing a pointer.") 19 } 20 for i := 0; i < tin.NumField(); i++ { 21 tinf := tin.Field(i) 22 toutf, ok := tout.FieldByName(tinf.Name) 23 if !ok { 24 continue 25 } 26 if !tinf.Type.AssignableTo(toutf.Type) { 27 continue 28 } 29 voutfv := vout.FieldByIndex(toutf.Index) 30 if !voutfv.CanSet() { 31 continue 32 } 33 voutfv.Set(vin.Field(i)) 34 } 35 }