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

Time:10-19

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 :

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 ?

CodePudding user response:

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
}
  • Related