type A struct {
One string
Two int
}
type B struct {
One string
Two int
}
func CopyStruct(src, dst interface{}) error {
sval := reflect.ValueOf(src).Elem()
dval := reflect.ValueOf(dst).Elem()
for i := 0; i < sval.NumField(); i++ {
val := sval.Field(i)
name := sval.Type().Field(i).Name
dvalue := dval.FieldByName(name)
if dvalue.IsValid() == false {
return errors.New("field cannot find")
}
dvalue.Set(val)
}
return nil
}
func main() {
a := &A{}
a.One = "hello"
a.Two = 2
b := New(B)
if err := CopyStruct(a, b); err != nil {
fmt.Println(err)
return
}
resB := *b
fmt.Println(resB)
}