package main
import (
"fmt"
"reflect"
)
type A struct {
Name string
Gender string
Age int
}
type B struct {
Name string
Gender string
}
//binding type interface 要修改的结构体
//value type interace 有数据的结构体
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
if ok := bVal.FieldByName(name).IsValid(); ok {
bVal.FieldByName(name).Set(reflect.ValueOf(vVal.Field(i).Interface()))
}
}
}
func main() {
as := A{}
bs := B{Name: "wfy", Gender: "男"}
fmt.Println(as)
structAssign(&as, &bs)
fmt.Println(as)
}
golang使用反射将一个结构体的数据直接复制到另一个结构体中(通过相同字段)
最新推荐文章于 2024-01-05 14:44:15 发布
9386

被折叠的 条评论
为什么被折叠?



