function for converting a struct to map in Golang

前端 未结 5 1304
囚心锁ツ
囚心锁ツ 2020-12-07 18:38

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).

Edi

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 19:13

    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.

提交回复
热议问题