type Data struct {
Name string `tag:"姓名"`
Age int8 `tag:"年龄"`
Class string `tag:"班级"`
}
func main() {
newData := &Data{
Name: "test",
Age: 3,
Class: "三班",
}
oldData := &Data{
Name: "test",
Age: 2,
Class: "五班",
}
info := diffAndWrite(oldData, newData)
fmt.Println(info)
}
func diffAndWrite(oldData, newData interface{}) string {
var (
oldRefElem = reflect.ValueOf(oldData).Elem()
newRefElem = reflect.ValueOf(newData).Elem()
refType = newRefElem.Type()
msgs = make([]string, 0)
)
for i := 0; i < newRefElem.NumField(); i++ {
n := refType.Field(i).Name
//v := refElem.Field(i)
t := refType.Field(i).Tag
oldValue := oldRefElem.FieldByName(n).Interface()
newValue := newRefElem.FieldByName(n).Interface()
if oldValue != newValue {
msg := fmt.Sprintf("字段 %v 从 %v 变更为 %v", t.Get("tag"), cast.ToString(oldValue), cast.ToString(newValue))
msgs = append(msgs, msg)
}
}
return strings.Join(msgs, "; ")
}
面向猴子编程 比较两个结构体并打印差异
于 2022-02-15 17:36:27 首次发布