当前位置:网站首页>golang使用反射将一个结构体的数据直接复制到另一个结构体中(通过相同字段)
golang使用反射将一个结构体的数据直接复制到另一个结构体中(通过相同字段)
2022-06-10 14:36:00 【Deng_Xian_Sheng】
// CopyStruct
// dst 目标结构体,src 源结构体
// 必须传入指针,且不能为nil
// 它会把src与dst的相同字段名的值,复制到dst中
func CopyStruct(dst, src interface{
}) {
dstValue := reflect.ValueOf(dst).Elem()
srcValue := reflect.ValueOf(src).Elem()
for i := 0; i < srcValue.NumField(); i++ {
srcField := srcValue.Field(i)
srcName := srcValue.Type().Field(i).Name
dstFieldByName := dstValue.FieldByName(srcName)
if dstFieldByName.IsValid() {
switch dstFieldByName.Kind() {
case reflect.Ptr:
switch srcField.Kind() {
case reflect.Ptr:
if srcField.IsNil() {
dstFieldByName.Set(reflect.Zero(dstFieldByName.Type()))
} else {
dstFieldByName.Set(srcField)
}
default:
dstFieldByName.Set(srcField.Addr())
}
default:
switch srcField.Kind() {
case reflect.Ptr:
if srcField.IsNil() {
dstFieldByName.Set(reflect.Zero(dstFieldByName.Type()))
} else {
dstFieldByName.Set(srcField.Elem())
}
default:
dstFieldByName.Set(srcField)
}
}
}
}
}
边栏推荐
- 碰撞检测 Unity实验代码
- ScrollView 初始化的时候不在最顶部?
- c#浅拷贝与深拷贝自定义的类的List<>
- 2022年危险化学品生产单位安全生产管理人员考试模拟100题及在线模拟考试
- Binary tree and figure 1
- [discrete mathematics review series] III. concept and operation of sets
- Cell asynchronously invokes method change records
- 洞見科技入選「愛分析· 隱私計算廠商全景報告」,獲評金融解决方案代錶廠商
- 利用 GDB 快速阅读 postgresql 的内核代码
- 数据湖(六):Hudi与Flink整合
猜你喜欢

还在说大学排名是笑话?最新规定:世界top50大学可以直接落户上海!

Main features of IIC bus / communication process / read / write process

初试c语言之第二次笔记

【LogoDetection 数据集处理】(2)画出训练集图片的标注框

Binary tree and figure 1

Meta公司新探索 | 利用Alluxio数据缓存降低Presto延迟

Beijing / Shanghai internal promotion | recruitment of full-time interns in the system and network group of Microsoft Research Asia

2022危险化学品经营单位主要负责人考试题库及在线模拟考试
![[discrete mathematics review series] v. some special charts](/img/4d/a52ba801b0421245d5e3828defc96d.png)
[discrete mathematics review series] v. some special charts

Gin blog summary 1
随机推荐
Consumption mode of Message Oriented Middleware
Allan variance and random error identification
【原创】POI 5.x XSSF和HSSF使用自定义字体颜色
what‘t the meaning of “de facto“
焱融看|混合云环境下,如何实现数据湖最优存储解决方案
Wechat applet returns to the previous page and transfers parameters
1
The interview at the big factory was held at 10:00 a.m. and came out at 10:09 a.m. the question was really too
Insight technology was selected into the "Aijian · privacy computing manufacturer panorama report" and was rated as a representative manufacturer of financial solutions
【LogoDetection 数据集处理】(3)将训练集按照类别划分为多个文件夹
互联网公司研发效能团队为啥必须独立?何时独立?
2022山东省安全员C证复训题库及在线模拟考试
博主自白
UE5如何將屏幕坐標轉為世界坐標和世界方向
[logodetection data set processing] (2) draw the label box of the training set picture
Beijing / Shanghai internal promotion | recruitment of full-time interns in the system and network group of Microsoft Research Asia
c#浅拷贝与深拷贝自定义的类的List<>
【离散数学期复习系列】四、图
Cell asynchronously invokes method change records
[cloud native | kubernetes] in depth RC, RS, daemonset, statefulset (VII)