============ 错误处理函数 (优化版) ============ SafeMapDirect 安全映射,忽略错误 使用示例: dto := mapper.SafeMapDirect[User, UserDTO](user)
(from From)
| 174 | // SafeMapDirect 安全映射,忽略错误 |
| 175 | // 使用示例: dto := mapper.SafeMapDirect[User, UserDTO](user) |
| 176 | func SafeMapDirect[From, To any](from From) (To, error) { |
| 177 | var result To |
| 178 | |
| 179 | fromVal := reflect.ValueOf(from) |
| 180 | if !fromVal.IsValid() { |
| 181 | return result, errors.New("invalid from value") |
| 182 | } |
| 183 | |
| 184 | // 处理指针类型 |
| 185 | if fromVal.Kind() == reflect.Ptr { |
| 186 | if fromVal.IsNil() { |
| 187 | return result, errors.New("from is nil pointer") |
| 188 | } |
| 189 | fromVal = fromVal.Elem() |
| 190 | } |
| 191 | |
| 192 | // 获取类型信息 |
| 193 | fromType := fromVal.Type() |
| 194 | toType := reflect.TypeOf(result) |
| 195 | |
| 196 | if toType.Kind() != reflect.Struct { |
| 197 | return result, nil |
| 198 | } |
| 199 | |
| 200 | // 尝试从缓存获取映射关系 |
| 201 | mappings, ok := getFieldMappings(fromType, toType) |
| 202 | if !ok { |
| 203 | mappings = buildFieldMappings(fromType, toType) |
| 204 | } |
| 205 | |
| 206 | // 创建目标值 |
| 207 | toVal := reflect.New(toType).Elem() |
| 208 | |
| 209 | // 执行映射 |
| 210 | for _, m := range mappings { |
| 211 | if len(m.fromIndex) > 0 { |
| 212 | fromFieldVal := fromVal.FieldByIndex(m.fromIndex) |
| 213 | toFieldVal := toVal.Field(m.toIndex) |
| 214 | if toFieldVal.CanSet() { |
| 215 | toFieldVal.Set(fromFieldVal) |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | return toVal.Interface().(To), nil |
| 221 | } |
| 222 | |
| 223 | // SafeMapDirectSlice 安全批量映射 |
| 224 | // 使用示例: dtos, err := mapper.SafeMapDirectSlice[User, UserDTO](users) |
nothing calls this directly
no test coverage detected
searching dependent graphs…