Last active
June 13, 2019 12:22
-
-
Save vchakoshy/0607a55362270b2f29692303f94bebc2 to your computer and use it in GitHub Desktop.
golang inject struct to another struct recursively
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
package main | |
import "reflect" | |
func InjectStrcut(a interface{}, b interface{}) { | |
v := reflect.ValueOf(a).Elem() | |
targetName := reflect.TypeOf(b).Name() | |
infector(v, b, targetName) | |
} | |
func infector(v reflect.Value, pd interface{}, name string) { | |
for j := 0; j < v.NumField(); j++ { | |
f := v.Field(j) | |
n := v.Type().Field(j).Name | |
// t := f.Type().Name() | |
if n == name && f.Kind() == reflect.Struct { | |
// fmt.Printf("Name: %s Kind: %s Type: %s\n", n, f.Kind(), t) | |
f.Set(reflect.ValueOf(pd)) | |
} else if f.Kind() == reflect.Struct { | |
infector(f, pd, name) | |
} | |
} | |
} |
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
package main | |
import "testing" | |
func TestInjectStrcut(t *testing.T) { | |
type profile struct { | |
Skills []string | |
} | |
type user struct { | |
ID int | |
Username string | |
Age int | |
Profile profile | |
} | |
u := user{ | |
ID: 1, | |
Username: "vchakoshy", | |
} | |
p := profile{ | |
Skills: []string{"Golang"}, | |
} | |
type args struct { | |
cs interface{} | |
pd interface{} | |
} | |
tests := []struct { | |
name string | |
args args | |
}{ | |
{ | |
name: "salam", | |
args: args{ | |
cs: &u, | |
pd: p, | |
}, | |
}, | |
} | |
for _, tt := range tests { | |
t.Run(tt.name, func(t *testing.T) { | |
InjectStrcut(tt.args.cs, tt.args.pd) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment