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

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

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

问题

我想定义一个类型Message,它基本上是一个具有两个特定键messagefrommap[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
}

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:

确定