貔貅云原生

貔貅云原生

反射对比结构体

88
0
0
2023-09-26
反射对比结构体
package main

import (
	"fmt"
	"reflect"
)

type User struct {
	Name   string `json:"name"`
	Age    int    `json:"age"`
	School string `json:"school"`
}

func main() {
	user1 := &User{
		Name: "jixingxing",
		Age:  18,
	}

	user2 := &User{
		Name: "yanglizi",
		Age:  18,
	}

	// 对比
	differences := compareStructs(*user1, *user2)

	if len(differences) == 0 {
		fmt.Println("The structures are identical.")
	} else {
		fmt.Println("Differences:")
		for _, diff := range differences {
			fmt.Println(diff)
		}
	}

}

// 不能传指针
func compareStructs(a, b interface{}) []string {
	var differences []string

	valA := reflect.ValueOf(a)
	valB := reflect.ValueOf(b)

	// 比对种类是不是结构体
	if valA.Kind() != reflect.Struct || valB.Kind() != reflect.Struct {
		diff := fmt.Sprintln("your value kinds is not struct type")
		differences = append(differences, diff)
		return differences
	}

	typeA := valA.Type()
	typeB := valB.Type()

	// 判断两个种类结构体是否相同
	if typeA != typeB {
		diff := fmt.Sprintln("the two data structures are different")
		differences = append(differences, diff)
		return differences
	}

	// 获取结构体里面类型数量
	for i := 0; i < typeA.NumField(); i++ {
		fieldA := valA.Field(i)
		fieldB := valB.Field(i)

		// interface 返回(current)当前值
		if fieldA.Interface() != fieldB.Interface() {
			diff := fmt.Sprintf("Field '%s': %v != %v", typeA.Field(i).Name, fieldA.Interface(), fieldB.Interface())
			differences = append(differences, diff)
		}
	}

	return differences
}