I'm trying to write a function which converts a byte array of JSON string to another in accordance with the type parameter of the return value as the following rule:
- map[string]interface{}: convert to map[string]interface{}
- []byte: no conversion, return as is
- struct: convert to the struc
My code is as follow:
func GetJsonData[T any](jsonByteArray []byte) (result *T, err error) {
var buff T
switch any(result).(type) { // https://appliedgo.com/blog/a-tip-and-a-trick-when-working-with-generics
case *[]byte:
result = &T(jsonByteArray)
default:
err = json.Unmarshal(jsonByteArray, &buff)
result = &buff
}
return
}
This code occurs following type error at the point of cast the type of jsonByteArray to T as follows:
cannot convert jsonByteArray (variable of type []byte) to type T
How can I assign the pointer of this []byte type variable to the generic type return value?