i read your code, and try to write my code, package main
import ( "fmt" "reflect" ) type A struct{ Name string } type B struct{ Age int } type C struct{ Address string } func Merge(a interface{}, b interface{})( d interface{}) { aType := reflect.TypeOf(a) if aType.Kind() != reflect.Struct { panic("a is not a struct") } bType := reflect.TypeOf(b) if bType.Kind() != reflect.Struct { panic("b is not a struct") } var fields []reflect.StructField for i:=0 ; i< aType.NumField(); i++{ fields =append(fields, aType.Field(i)) } for i:=0 ; i< bType.NumField(); i++{ fields =append(fields, bType.Field(i)) } dType := reflect.StructOf(fields) dVal := reflect.Indirect(reflect.New(dType)) aVal := reflect.ValueOf(a) bVal := reflect.ValueOf(b) for i := 0; i < aType.NumField(); i++ { dVal.FieldByName(aType.Field(i).Name).Set(aVal.Field(i)) } for i := 0; i < bType.NumField(); i++ { dVal.FieldByName(bType.Field(i).Name).Set(bVal.Field(i)) } d = dVal.Interface() return } func main() { a, b, c := A{"John"}, B{42}, C{"World"} d1 := Merge(a, b) d2 := Merge(a, c) d3 := Merge(b, c) fmt.Printf("%#v\n",d1) fmt.Printf("%#v\n",d2) fmt.Printf("%#v\n",d3) } output, it's my want struct { Name string; Age int }{Name:"John", Age:42} struct { Name string; Address string }{Name:"John", Address:"World"} struct { Age int; Address string }{Age:42, Address:"World"} thanks all people 在 2019年8月24日星期六 UTC+8下午6:12:40,Jacques Supcik写道: > > As suggested by Kurtis Rader, I would use "reflection" for this. > > Here is a simple example (not fully tested, probably not safe, not > production ready... so just for demonstration purpose) : > > https://play.golang.org/p/sAyBajxsTAN > > -- Jacques > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/818167f3-47cd-46e7-a5b3-bb6bd1f51c27%40googlegroups.com.