Golang动态创建Struct的成员 [英] Golang dynamic creating member of Struct

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

问题描述

我对Golang相当陌生。我知道Golang中有Struct。但是对于我所知道的,你必须定义struct

 类型Circle结构{
x,y,r float64

我想知道如何声明一个不存在于Struct中的新变量

  circle:= new(Cirlce)
circle.color =black

Thx提前。

解决方案

您需要使用映射(类型为 map [string] interface {} )来处理动态JSON。这是一个创建新地图的例子:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ bm:= map [string] interface { } {
key:value,
}

//动态添加一个子映射
m [sub] = map [string] interface {} {
deepKey:deepValue,
}

解组JSON到一个映射如下所示:

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

上面的代码会在 f ,结构类似于:

  f = map [string] interface {} {
姓名:星期三,
年龄:6,
父母:[]界面{} {
戈麦斯,
Morticia,




$ b

你将需要使用一个类型断言来访问它,

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

您也会需要在您从地图中拉出的每个项目上使用断言或类型开关。处理非结构化JSON是一件麻烦事。



更多信息:


I am fairly new to Golang. I know there is Struct in Golang. 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(Cirlce)
circle.color = "black"

Thx in advance.

解决方案

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",
}

Unmarshalling JSON into a map looks like:

var f interface{}
err := json.Unmarshal(b, &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",
    },
}

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{})

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.

More information:

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

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