Skip to content

Instantly share code, notes, and snippets.

@yasarix
Last active February 7, 2017 17:26
Show Gist options
  • Save yasarix/38ed17e23a64440b8bc3fc40f03ab70f to your computer and use it in GitHub Desktop.
Save yasarix/38ed17e23a64440b8bc3fc40f03ab70f to your computer and use it in GitHub Desktop.
package main
import (
"reflect"
)
// StructCopy Copies the common field values from source to target. Pass the pointers of the interfaces
func StructCopy(source interface{}, target interface{}) {
sourceElem := reflect.ValueOf(source).Elem()
targetElem := reflect.ValueOf(target).Elem()
for i := 0; i < sourceElem.NumField(); i++ {
sourceField := sourceElem.Type().Field(i)
targetField := targetElem.FieldByName(sourceField.Name)
if targetField.Kind() == sourceElem.Field(i).Kind() {
targetField.Set(reflect.Value(sourceElem.Field(i)))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment