英文:
GO : Define a type which is Map with 2 specifique Key
问题
我想定义一个类型Message,它基本上是一个具有两个特定键message和from的map[string]string。
一个Message应该是:
map[string]string{"message": "Hello", "from": "Me"}
我定义了一个类型Message:
type Message struct {
    message string,
    from string
}
注意:我需要将这个Message转换为JSON格式,以便通过HTTP请求发送,这就是为什么我“需要”使用map[string]string的原因。我最终发现也可以将结构体序列化为JSON对象。
在Go语言中,是否可以定义一个具有特定键的map类型?在Go语言中,如何以惯用的方式解决这个问题?
英文:
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
}
Note : I need to convert this Message to json in order to send it though http request, that's why I "need" to use map[string]string => I finnaly found out that it's also possible to serialized struct as JSON objects
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 ?
答案1
得分: 2
根据问题中的评论所透露的信息,偏好使用map[string]string的原因是为了保留JSON编码。然而,结构体也可以被序列化为JSON对象。
import "encoding/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 {
  // 处理错误
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论