MCPcopy Index your code
hub / github.com/APIParkLab/APIPark / MapStringToStruct

Function MapStringToStruct

module/system/dto/output.go:14–65  ·  view source on GitHub ↗
(m map[string]string)

Source from the content-addressed store, hash-verified

12}
13
14func MapStringToStruct[T any](m map[string]string) *T {
15 var result T
16 val := reflect.ValueOf(&result).Elem()
17
18 // 获取结构体的类型
19 t := val.Type()
20
21 // 查找结构体中与键名匹配的字段
22 for i := 0; i < t.NumField(); i++ {
23 field := t.Field(i)
24 key := field.Tag.Get("key")
25 if key == "" {
26 continue
27 }
28 v, ok := m[key]
29 if !ok {
30 continue
31 }
32 // 获取字段的值
33 fieldVal := val.Field(i)
34 if !fieldVal.CanSet() {
35 continue
36 }
37 fieldVal.SetString(v)
38
39 // 如果字段不可设置,跳过
40 if !fieldVal.CanSet() {
41 continue
42 }
43
44 // 根据字段的类型,进行类型转换
45 switch fieldVal.Kind() {
46 case reflect.Float64:
47 // 如果是 string 类型且非空,转换为 float64
48 if floatVal, err := strconv.ParseFloat(v, 64); err == nil {
49 fieldVal.SetFloat(floatVal)
50 }
51
52 case reflect.Int:
53
54 if intVal, err := strconv.Atoi(v); err == nil {
55 fieldVal.SetInt(int64(intVal))
56 }
57 case reflect.String:
58 fieldVal.SetString(v)
59 default:
60 // 其他类型不进行转换
61 }
62 }
63
64 return &result
65}

Callers

nothing calls this directly

Calls 2

TypeMethod · 0.65
GetMethod · 0.65

Tested by

no test coverage detected