在Golang中将结构转换为地图的函数 [英] function for converting a struct to map in Golang

查看:110
本文介绍了在Golang中将结构转换为地图的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Golang中将结构转换为地图。如果我可以在创建的地图中使用JSON标签作为关键字(否则默认为字段名称),那也不错。



编辑TL; DR版本,Jun 15, 2015



如果您想要将结构转换为地图的快速解决方案,请参阅接受答案,upvote它并使用该包。



快乐编码! :)






原始文章



到目前为止,功能,我正在使用反射包,但我不明白如何使用该包,请耐心等待。

  func ConvertToMap(model interface {})bson.M {
ret:= bson.M {}

modelReflect:= reflect.ValueOf(model)

if modelReflect.Kind()== reflect.Ptr {
modelReflect = modelReflect.Elem()
}

modelRefType:= modelReflect.Type()
fieldsCount:= modelReflect.NumField()

var fieldData接口{}

for i:= 0;我< fieldsCount; i ++ {
field:= modelReflect.Field(i)

switch field.Kind(){
case reflect.Struct:
through
case reflect .Ptr:
fieldData = ConvertToMap(field.Interface())
默认值:
fieldData = field.Interface()
}

ret [modelRefType .Field(i).Name] = fieldData
}

return ret
}

我还查看了JSON包源代码,因为它应该包含我需要的实现(或其中的一部分),但不太了解。

解决方案

我也需要这样的东西。我正在使用将结构转换为地图的内部软件包。我决定用其他基于高级函数的 struct 开源。看一看:



https://github.com/fatih/structs



支持:


  • 将结构转换为地图

  • 将结构的字段提取为 []字符串

  • 提取a结构为 []值

  • 检查结构是否被初始化

  • 检查如果一个传入的接口是一个struct或一个指向struct的指针

    $ b

    你可以在这里看到一些例子:http://godoc.org/github.com/fatih/structs#pkg-examples
    例如将一个结构到一个映射是一个简单的:

    pre $ 类型服务器结构{
    名称字符串
    ID int32
    已启用bool
    }

    s:=& Server {
    名称:gopher,
    ID:123456,
    启用:true,
    }

    // => {Name:gopher,ID:123456,Enabled:true}
    m:= structs.Map(s)


    $ b structs 包支持匿名(嵌入)字段和嵌套结构。该软件包提供了通过字段标记过滤某些字段。

    I want to convert a struct to map in Golang. It would also be nice if I could use the JSON tags as keys in the created map (otherwise defaulting to field name).

    Edit TL;DR version, Jun 15, 2015

    If you want the fast solution for converting a structure to map, see the accepted answer, upvote it and use that package.

    Happy coding! :)


    Original Post

    So far I have this function, I am using the reflect package but I don't understand well how to use the package, please bear with me.

    func ConvertToMap(model interface{}) bson.M {
        ret := bson.M{}
    
        modelReflect := reflect.ValueOf(model)
    
        if modelReflect.Kind() == reflect.Ptr {
            modelReflect = modelReflect.Elem()
        }
    
        modelRefType := modelReflect.Type()
        fieldsCount := modelReflect.NumField()
    
        var fieldData interface{}
    
        for i := 0; i < fieldsCount; i++ {
            field := modelReflect.Field(i)
    
            switch field.Kind() {
            case reflect.Struct:
                fallthrough
            case reflect.Ptr:
                fieldData = ConvertToMap(field.Interface())
            default:
                fieldData = field.Interface()
            }
    
            ret[modelRefType.Field(i).Name] = fieldData
        }
    
        return ret
    }
    

    Also I looked at JSON package source code, because it should contain my needed implementation (or parts of it) but don't understand too much.

    解决方案

    I also had need for something like this. I was using an internal package which was converting a struct to a map. I decided to open source it with other struct based high level functions. Have a look:

    https://github.com/fatih/structs

    It has support for:

    • Convert struct to a map
    • Extract the fields of a struct to a []string
    • Extract the values of a struct to a []values
    • Check if a struct is initialized or not
    • Check if a passed interface is a struct or a pointer to struct

    You can see some examples here: http://godoc.org/github.com/fatih/structs#pkg-examples For example converting a struct to a map is a simple:

    type Server struct {
        Name    string
        ID      int32
        Enabled bool
    }
    
    s := &Server{
        Name:    "gopher",
        ID:      123456,
        Enabled: true,
    }
    
    // => {"Name":"gopher", "ID":123456, "Enabled":true}
    m := structs.Map(s)
    

    The structs package has support for anonymous (embedded) fields and nested structs. The package provides to filter certain fields via field tags.

    这篇关于在Golang中将结构转换为地图的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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