123456789101112131415161718192021222324252627 |
- package utils
- import (
- "fmt"
- "reflect"
- )
- func CopyWithReflection(src interface{}, dst interface{}) error {
- srcValue := reflect.ValueOf(src)
- dstValue := reflect.ValueOf(dst)
- if srcValue.Kind() != reflect.Struct || dstValue.Kind() != reflect.Struct {
- return fmt.Errorf("both src and dst must be structs")
- }
- for i := 0; i < srcValue.NumField(); i++ {
- srcField := srcValue.Field(i)
- dstField := dstValue.FieldByName(srcValue.Type().Field(i).Name)
- if !dstField.IsValid() {
- continue // 如果目标结构体没有该字段,则跳过
- }
- // 检查类型是否匹配,如果需要转换类型,可以在这里添加转换代码
- if srcField.Type() != dstField.Type() {
- return fmt.Errorf("field types don't match: %s", srcValue.Type().Field(i).Name)
- }
- dstField.Set(srcField)
- }
- return nil
- }
|