samedi 26 juin 2021

How to declare the Type of a variable dynamically in GO, using if-else-like conditions?

Given two types

type A struct {
    ID         string
    Content    []int
}

and

type B struct {
    ID         string
    Content    map[string][]int
}

and I need a function to tell me which type to use hereafter according to conditions (the purpose is to unmarshal a json string properly). I want a function like

func assign_typed_data(header string) interface{} {
    switch header {
    case "A" :
         d := new(A)
         fmt.Printf('inner type is %T \n', *d)      // inner type is A
         return *d
    case "B" :
         d := new(B)
         fmt.Printf('inner type is %T \n', *d)      // inner type is B
         return *d
    default:
    }
}

and in the outer code I can call it and unmarshal the json like follows, but the returned value turns to "map[string]interface{}".

header := "A"
data := assign_typed_data(header)
fmt.Printf('outter type is %T \n', data)      // outter type is map[string]interface{}
json.Unmarshal(json_data, &data)

I also tried simple if-else statements in the outter code directly without calling a function, like follows, but failed as well because of defined scope is local.

if header == "A" {
    data := *new(A)
}else if header == "B" {
    data := *new(B)
}
json.Unmarshal(json_data, &data)

Is there a possible way to achieve this goal in GO?

Aucun commentaire:

Enregistrer un commentaire