Last active
August 1, 2016 02:26
-
-
Save legendtkl/1efe494dc4830a2800bc4c1276e52ffd to your computer and use it in GitHub Desktop.
在golang 做orm的时候经常有这样一个场景:两个struct有部分相同的成员(名字和类型)。如果拷贝struct中这些字段的话逐个拷贝就会比较耗费时间,下面代码使用reflect实现了拷贝。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func CopyStruct(src, dst interface{}) { | |
sval := reflect.ValueOf(src).Elem() | |
dval := reflect.ValueOf(dst).Elem() | |
for i := 0; i < sval.NumField(); i++ { | |
value := sval.Field(i) | |
name := sval.Type().Field(i).Name | |
dvalue := dval.FieldByName(name) | |
if dvalue.IsValid() == false { | |
continue | |
} | |
typ := sval.Type().Field(i).Type | |
switch typ.Kind() { | |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: | |
if dvalue.Int() == 0 { | |
dvalue.SetInt(value.Int()) | |
} | |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: | |
if dvalue.Uint() == 0 { | |
dvalue.SetUint(value.Uint()) | |
} | |
case reflect.Float32, reflect.Float64: | |
if dvalue.Float()-0.0 < 0.01 { | |
dvalue.SetFloat(value.Float()) | |
} | |
case reflect.String: | |
if dvalue.String() == "" { | |
dvalue.SetString(value.String()) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment