Golang动态创建结构体成员 [英] Golang dynamically creating member of struct

查看:172
本文介绍了Golang动态创建结构体成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Go 中有 struct,但就我所知,你必须定义 struct

I know there is struct in Go, but for all I know, you have to define struct

type Circle struct{
    x,y,r float64
}

我想知道如何声明结构中不存在的新变量

I am wondering how you can declare a new variable that doesn't exist in the struct

circle := new(Circle)
circle.color = "black"

推荐答案

您将需要使用地图(map[string]interface{} 类型)来处理动态 JSON.以下是创建新地图的示例:

You will need to use a map (of type map[string]interface{}) to work with dynamic JSON. Here is an example of creating a new map:

// Initial declaration
m := map[string]interface{}{
    "key": "value",
}

// Dynamically add a sub-map
m["sub"] = map[string]interface{}{
    "deepKey": "deepValue",
}

将 JSON 解组为地图如下所示:

Unmarshalling JSON into a map looks like:

var f interface{}
err := json.Unmarshal(b, &f)

上面的代码会在 f 中留下一张地图,其结构类似于:

The code above would leave you with a map in f, with a structure resembling:

f = map[string]interface{}{
    "Name": "Wednesday",
    "Age":  6,
    "Parents": []interface{}{
        "Gomez",
        "Morticia",
    },
}

你需要使用类型断言来访问它,否则 Go 不会知道它是一个地图:

You will need to use a type assertion to access it, otherwise Go won't know it's a map:

m := f.(map[string]interface{})

您还需要在从地图中拉出的每个项目上使用断言或类型开关.处理非结构化 JSON 很麻烦.

You will also need to use assertions or type switches on each item you pull out of the map. Dealing with unstructured JSON is a hassle.

更多信息:

这篇关于Golang动态创建结构体成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆