Last active
May 23, 2019 11:23
-
-
Save anshuraj/36d9fa6ad540b2d55d6e2dd3a186cdf3 to your computer and use it in GitHub Desktop.
This file contains 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
// assign Copy one struct into another of same type | |
// Accepts pointer to struct | |
func assign(t interface{}, t2 interface{}) { | |
s := reflect.ValueOf(t) | |
s2 := reflect.ValueOf(t2) | |
if s.Kind() == reflect.Ptr { | |
s = reflect.Indirect(s) | |
} | |
if s2.Kind() == reflect.Ptr { | |
s2 = reflect.Indirect(s2) | |
} | |
if s.Kind() != reflect.Struct || s2.Kind() != reflect.Struct { | |
log.Fatal("unexpected type 1") | |
} | |
num := s.NumField() | |
for i := 0; i < num; i++ { | |
f := s.Field(i) | |
f2 := s2.Field(i) | |
if reflect.Value(f).String() != "" && f.CanSet() { | |
f2.Set(reflect.Value(f)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment