为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用类似 if-else 的条件在 GO 中动态声明变量的类型?

如何使用类似 if-else 的条件在 GO 中动态声明变量的类型?

Go
Smart猫小萌 2022-09-12 16:02:05
给定两种类型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中实现这一目标?
查看完整描述

1 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

您必须将指向预期数据类型的指针传递给 json。昂马歇尔()。即,或 .*A*B


然而,返回并获取其地址,因此您将通过.assign_typed_data()interface{}*interface{}


更改为返回指针值 或 ,并按原样传递给,因为它已经包含指针值:assign_typed_data()*A*Bdatajson.Unmarshal()


func createValue(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:

        return nil

    }

}

测试它:


s := `{"ID":"abc","Content":[1,2,3]}`

data := createValue("A")

if err := json.Unmarshal([]byte(s), data); err != nil {

    panic(err)

}

fmt.Printf("outer type is %T \n", data)

fmt.Printf("outer value is %+v \n", data)


s = `{"ID":"abc","Content":{"one":[1,2], "two":[3,4]}}`

data = createValue("B")

if err := json.Unmarshal([]byte(s), data); err != nil {

    panic(err)

}

fmt.Printf("outer type is %T \n", data)

fmt.Printf("outer value is %+v \n", data)

哪些输出(在Go游乐场上尝试):


inner type is *main.A 

outer type is *main.A 

outer value is &{ID:abc Content:[1 2 3]} 

inner type is *main.B 

outer type is *main.B 

outer value is &{ID:abc Content:map[one:[1 2] two:[3 4]]} 

请检查相关/可能的重复项,以进一步详细说明问题:

高浪接口{} 类型误区

是否可以动态设置 json 的输出。不合时宜?

如何告诉 json.取消使用结构而不是接口


查看完整回答
反对 回复 2022-09-12
  • 1 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号