Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge two structs in Golang?

Tags:

I have two json-marshallable anonymous structs.

a := struct {     Name string `json:"name"` }{"my name"}  b := struct {     Description string `json:"description"` }{"my description"} 

Is there any way to merge them into json to get something like that:

{     "name":"my name",     "description":"my description" } 
like image 579
Dmitry Kapsamun Avatar asked Nov 09 '16 14:11

Dmitry Kapsamun


2 Answers

You can embed both structs in another.

type name struct {     Name string `json:"name"` }  type description struct {     Description string `json:"description"` }  type combined struct {     name     description } 

The JSON package will treat embedded structs kind of like unions, but this can get clunky pretty quickly.

like image 135
nothingmuch Avatar answered Oct 04 '22 01:10

nothingmuch


It's a bit convoluted but I suppose you could do something like this:

    a := struct {         Name string `json:"name"`     }{"my name"}      b := struct {         Description string `json:"description"`     }{"my description"}      var m map[string]string      ja, _ := json.Marshal(a)     json.Unmarshal(ja, &m)     jb, _ := json.Marshal(b)     json.Unmarshal(jb, &m)      jm, _ := json.Marshal(m)     fmt.Println(string(jm)) 
like image 40
Franck Jeannin Avatar answered Oct 04 '22 01:10

Franck Jeannin