============ 函数式泛型 Mapper (优化版) ============ MapDirect 同构/异构映射,直接返回结果 使用示例: dto := mapper.MapDirect[User, UserDTO](user)
(from From)
| 72 | // MapDirect 同构/异构映射,直接返回结果 |
| 73 | // 使用示例: dto := mapper.MapDirect[User, UserDTO](user) |
| 74 | func MapDirect[From, To any](from From) To { |
| 75 | var result To |
| 76 | |
| 77 | fromVal := reflect.ValueOf(from) |
| 78 | if !fromVal.IsValid() { |
| 79 | return result |
| 80 | } |
| 81 | |
| 82 | // 处理指针类型 |
| 83 | if fromVal.Kind() == reflect.Ptr { |
| 84 | if fromVal.IsNil() { |
| 85 | return result |
| 86 | } |
| 87 | fromVal = fromVal.Elem() |
| 88 | } |
| 89 | |
| 90 | // 获取类型信息 |
| 91 | fromType := fromVal.Type() |
| 92 | toType := reflect.TypeOf(result) |
| 93 | |
| 94 | if toType.Kind() != reflect.Struct { |
| 95 | return result |
| 96 | } |
| 97 | |
| 98 | // 尝试从缓存获取映射关系 |
| 99 | mappings, ok := getFieldMappings(fromType, toType) |
| 100 | if !ok { |
| 101 | mappings = buildFieldMappings(fromType, toType) |
| 102 | } |
| 103 | |
| 104 | // 创建目标值 |
| 105 | toVal := reflect.New(toType).Elem() |
| 106 | |
| 107 | // 执行映射 |
| 108 | for _, m := range mappings { |
| 109 | if len(m.fromIndex) > 0 { |
| 110 | fromFieldVal := fromVal.FieldByIndex(m.fromIndex) |
| 111 | toFieldVal := toVal.Field(m.toIndex) |
| 112 | if toFieldVal.CanSet() { |
| 113 | toFieldVal.Set(fromFieldVal) |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | return toVal.Interface().(To) |
| 119 | } |
| 120 | |
| 121 | // MapDirectPtr 指针版本 |
| 122 | // 使用示例: dto := mapper.MapDirectPtr[User, UserDTO](&user) |
nothing calls this directly
no test coverage detected
searching dependent graphs…