
golang结构体深度对比处理
有三个结构体a, b, c,结构体都相同,但a和b之间有些值不同。现在需要获取这些不同值,进行处理后赋值给c。
解决方案
可以使用反射机制自动获取结构体的成员名、成员类型、成员值,然后对它们进行操作,实现不同值的获取和赋值。具体代码如下:
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"fmt"
"reflect"
)
type person struct {
name string
age uint8
married bool
hobbies []string
education map[string]string
}
func main() {
a := person{
name: "john",
age: 19,
married: false,
hobbies: []string{"dance", "music"},
education: map[string]string{"university": "xx school"},
}
b := person{
name: "jim",
age: 19,
married: false,
hobbies: []string{"singing", "music"},
education: map[string]string{"university": "xx school"},
}
c := person{}
// 获取结构体的 reflect.value 和 reflect.type 对象
avalue := reflect.valueof(a)
atype := reflect.typeof(a)
bvalue := reflect.valueof(b)
// 需要使用 c 的引用,因为后面需要给 c 赋值
cvalue := reflect.valueof(&c)
// 遍历结构体的字段
for i := 0; i < avalue.numfield(); i++ {
// 获取当前字段的 value 和 type 对象
afield := avalue.field(i)
afieldtype := atype.field(i)
// 获取 b 结构体对应字段的 value 对象
bfield := bvalue.field(i)
// 打印不同字段的信息
fmt.printf("%v: %v - %v\n", afieldtype.name, afield.interface(), bfield.interface())
fmt.printf("========================\n")
// 对切片和 map 类型进行特殊处理
switch afield.kind() {
case reflect.map:
// 断言成 map 类型,比较键值对
aedu := afield.interface().(map[string]string)
bedu := bfield.interface().(map[string]string)
fmt.printf("%+v - %+v\n", aedu, bedu)
case reflect.slice:
// 用类似方式处理切片
default:
// 其他类型的字段,直接赋值给 c
if afield.interface() != bfield.interface() {
cvalue.elem().field(i).set(afield)
} else {
cvalue.elem().field(i).set(bfield)
}
}
}
fmt.printf("%+v\n", c)
}输出结果:
Name: John - Jim
========================
Age: 19 - 19
========================
Married: false - false
========================
Hobbies: [dance music] - [singing music]
========================
Education: map[university:xx school] - map[university:xx school]
========================
map[university:xx school] - map[university:xx school]
{Name:John Age:19 Married:false Hobbies:[] Education:map[]}以上就是如何使用 Golang 结构体反射机制实现不同结构体字段值的获取和赋值?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号