Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

GO : Define a type which is Map with 2 specifique Key

I want to define a type Message which is basically a map[string]string with 2 specific keys : message and from.

A Message should be :

map[string]string{"message": "Hello", "from": "Me"}

I defined a type Message :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type Message struct {
    message string,
    from string
}

But here, Message isn’t a map and it would be preferable Message to be a map
It is possible to defined a type which is a map with specific key with go ?
What would be the idiomatic solution to do this in Go ?

>Solution :

As revealed in the comments on the question, the reason for preferring map[string]string is to preserve JSON encoding. However, structs can be serialized as JSON objects

import "json"

type Message struct {
    Message string `json:"message"`
    From    string `json:"from"`
}

myMessage := Message{Message: "foo", From: "bar"};
serialized, err := json.Marshal(myMessage);
if err != nil {
  // handle the error
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading