MCPcopy Index your code
hub / github.com/apache/devlake / Convert

Function Convert

backend/core/utils/json.go:48–75  ·  view source on GitHub ↗

Convert converts value to type T. If value is a slice, it converts each element of the slice to type T. Does not support nested slices.

(value any)

Source from the content-addressed store, hash-verified

46// Convert converts value to type T. If value is a slice, it converts each element of the slice to type T.
47// Does not support nested slices.
48func Convert[T any](value any) (T, errors.Error) {
49 var t T
50 tType := reflect.TypeOf(t)
51 if tType.Kind() == reflect.Slice {
52 valueSlice, ok := value.([]any)
53 if !ok {
54 return t, errors.Default.New("Value is not a slice")
55 }
56 elemType := tType.Elem()
57 result := reflect.MakeSlice(tType, 0, len(valueSlice))
58 for i, v := range valueSlice {
59 value := reflect.ValueOf(v)
60 if elemType.AssignableTo(reflect.TypeOf(v)) {
61 elem := value.Convert(elemType)
62 result = reflect.Append(result, elem)
63 } else {
64 return t, errors.Default.New(fmt.Sprintf("Element %d is not of type %s", i, elemType.Name()))
65 }
66 }
67 return result.Interface().(T), nil
68 } else {
69 result, ok := value.(T)
70 if !ok {
71 return t, errors.Default.New(fmt.Sprintf("Value is not of type %T", t))
72 }
73 return result, nil
74 }
75}
76
77func ToJsonString(x any) string {
78 b, err := json.Marshal(x)

Callers

nothing calls this directly

Calls 3

NewMethod · 0.65
NameMethod · 0.65
ConvertMethod · 0.45

Tested by

no test coverage detected