MCPcopy Index your code
hub / github.com/devfeel/mapper / MapDirect

Function MapDirect

mapper_func.go:74–119  ·  view source on GitHub ↗

============ 函数式泛型 Mapper (优化版) ============ MapDirect 同构/异构映射,直接返回结果 使用示例: dto := mapper.MapDirect[User, UserDTO](user)

(from From)

Source from the content-addressed store, hash-verified

72// MapDirect 同构/异构映射,直接返回结果
73// 使用示例: dto := mapper.MapDirect[User, UserDTO](user)
74func 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)

Callers

nothing calls this directly

Calls 3

getFieldMappingsFunction · 0.85
buildFieldMappingsFunction · 0.85
SetMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…