给定两种类型
type A struct {
ID string
Content []int
}
和
type B struct {
ID string
Content map[string][]int
}
我需要一个函数来告诉我根据条件以后要使用哪种类型(目的是正确取消marshar字符串)。我想要一个像这样的函数
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:
}
}
在外部代码中,我可以调用它并取消marshaj,如下所示,但返回的值变为“map[string]接口{}”。
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)
我还在 outter 代码中直接尝试了简单的 if-else 语句,而不调用函数,如下所示,但由于定义的作用域是本地的,因此也失败了。
if header == "A" {
data := *new(A)
}else if header == "B" {
data := *new(B)
}
json.Unmarshal(json_data, &data)
有没有一种可能的方法可以在GO中实现这一目标?
aluckdog
相关分类