定义一个类型,该类型是具有两个特定键的映射(Map)。

huangapple go评论101阅读模式
英文:

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

问题

我想定义一个类型Message,它基本上是一个具有两个特定键messagefrommap[string]string

一个Message应该是:

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

我定义了一个类型Message

  1. type Message struct {
  2. message string,
  3. from string
  4. }

注意:我需要将这个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 :

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

I defined a type Message :

  1. type Message struct {
  2. message string,
  3. from string
  4. }

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对象。

  1. import "encoding/json"
  2. type Message struct {
  3. Message string `json:"message"`
  4. From string `json:"from"`
  5. }
  6. myMessage := Message{Message: "foo", From: "bar"}
  7. serialized, err := json.Marshal(myMessage)
  8. if err != nil {
  9. // 处理错误
  10. }
英文:

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

  1. import "json"
  2. type Message struct {
  3. Message string `json:"message"`
  4. From string `json:"from"`
  5. }
  6. myMessage := Message{Message: "foo", From: "bar"};
  7. serialized, err := json.Marshal(myMessage);
  8. if err != nil {
  9. // handle the error
  10. }

huangapple
  • 本文由 发表于 2022年10月19日 01:12:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/74114899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定