Quantcast
Channel: User Norbert - Stack Overflow
Viewing all articles
Browse latest Browse all 42

Answer by Norbert for Converting A struct to map using generics

$
0
0

While golang has generics, you are trying to make a generic map, which as far as I know will not work: The inferred type has to be one of the types only:

E.g. Input 3 different types, the inference for the strict returned map of either string, int64 or float64 does not work and you have to provided the compiler with extra information. The or is the important word in the documentation (see the getting started guide https://go.dev/doc/tutorial/generics)

package mainimport ("encoding/json""fmt")type Data interface {    int64 | float64 | string}type Server struct {    Name    string    ID      int32    Enabled bool}func ConvertStructToMap[V Data](in interface{}) map[string]V {    var inInterface map[string]V    inrec, _ := json.Marshal(in)    json.Unmarshal(inrec, &inInterface)    return inInterface}func main() {    s := &Server{        Name:    "gopher",        ID:      123456,        Enabled: true,    }    conv := ConvertStructToMap[int64](s)    fmt.Println(conv)}

So with generics you are not going to get where you want unless you want to parse out 1 type only. Still a type check (reflection as mentioned in the comments) would work better.

Alternative: json.RawMessage

If you define a map[string]json.RawMessage, you can use that to decode the information further by having individual calls per element using either reflection, e.(type), or generics to parse out that type. You might still run into the inference issue, in which case instead of json.RawMessage just the map[string]interface{} might have to be used


Viewing all articles
Browse latest Browse all 42

Latest Images

Trending Articles





Latest Images