猿问

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

给定两种类型


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中实现这一目标?


Smart猫小萌
浏览 114回答 1
1回答

aluckdog

您必须将指向预期数据类型的指针传递给 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.取消使用结构而不是接口
随时随地看视频慕课网APP

相关分类

Go
我要回答