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)
| 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. |
| 48 | func 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 | |
| 77 | func ToJsonString(x any) string { |
| 78 | b, err := json.Marshal(x) |