dongliuxia9495
2016-11-12 03:19
浏览 1.4k
已采纳

Golang动态创建成员Struct

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.

图片转代码服务由CSDN问答提供 功能建议

我刚接触Golang。 我知道Golang中有Struct。 但据我所知,您必须定义struct

  type Circle struct {
x,y,r float64 
} 
   \  n 
 

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

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

Thx。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongxian0421 2016-11-12 23:33
    已采纳

    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:

    已采纳该答案
    打赏 评论
  • dqpwdai095465 2016-11-12 08:32

    You can't. Go is statically typed, and does not allow such constructs.

    Structs have a layout in memory that directly related to the definition, and there's no where to store such additional fields.

    You can use a map instead. Moreover, you can use &circle as a key or part of a key, to associate map elements with arbitrary structs.

    type key struct {
        target interface{}
        field string
    }
    
    x := make(map[key]string)
    x[key{ target: circle, field: "color" }] = "black"
    
    打赏 评论
  • doyz51819 2019-01-05 21:14

    I've started to work on this small repository https://github.com/Ompluscator/dynamic-struct

    It's possible at this point to extend existing struct in runtime, by passing a instance of struct and modifying fields (adding, removing, changing types and tags).

    Still in progress, so don't expect something huge :)

    EDIT: At this point, work on library is done, and it looks stable for last a couple of months :)

    打赏 评论

相关推荐 更多相似问题