package main
import (
"fmt"
"reflect"
"time"
)
type TA struct {
Id *int32 `json:"id"`
TT TT `json:"tt"`
Arr Array[int32] `json:"arr"`
Date Datetime `json:"date"`
}
type TB struct {
Id *int32 `json:"id"`
TT TT `json:"tt"`
Arr Array[int32] `json:"arr"`
Date Datetime `json:"date"`
}
type Array[T string | int32 | int8] []T
type Datetime time.Time
type TT struct {
Id int32 `json:"id"`
}
func main() {
var num int32 = 1
a := TA{
Id: &num,
TT: TT{
Id: 2,
},
Arr: []int32{1, 2},
Date: Datetime(time.Now()),
}
var b TB
StructAssign(&b, &a)
fmt.Printf("%#v\n", a)
fmt.Printf("%#v\n", b)
}
func StructAssign(binding interface{}, value interface{}) {
bVal := reflect.ValueOf(binding).Elem() // 获取reflect.Type类型
vVal := reflect.ValueOf(value).Elem() // 获取reflect.Type类型
vTypeOfT := vVal.Type()
for i := 0; i < vVal.NumField(); i++ {
// 相同属性的字段,有则修改其值
name := vTypeOfT.Field(i).Name
// 同类型
valType := vTypeOfT.Field(i).Type
if ok := bVal.FieldByName(name).IsValid() && bVal.FieldByName(name).Type() == valType; ok {
bVal.FieldByName(name).Set(reflect.ValueOf(vVal.Field(i).Interface()))
}
}
}
标签:int32,type,TT,reflect,json,测试,go,Type,赋值
From: https://www.cnblogs.com/burndust/p/16646856.html