如何为函数签名定义一个 JSON 结构类型?

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

How to define a json struct type for function signature?

问题

我有一个结构体定义:

type ds struct {
    name     string
    TagList  []struct {
        Key   string `json:"Key"`
        Value string `json:"Value"`
    } `json:"TagList"`
}

我想要一个将TagList转换为字符串数组的函数(自定义序列化函数)。所以这个函数看起来会像这样:

func serialize(tagList <?>) string

我不确定应该如何定义<?>这个类型。因为如果我使用以下方式调用这个函数:

serialize(mydata.TagList)  // mydata是ds结构体类型

它会提醒我这个类型是[]struct{...}

但是我不确定如何定义[]struct{...}

我也可以使用现有的序列化库API来完成这个操作,只要它能将数据序列化为字符串即可。

英文:

I have a struct definition

type ds struct {
    name     string
	TagList                          []struct {
		Key   string `json:&quot;Key&quot;`
		Value string `json:&quot;Value&quot;`
	} `json:&quot;TagList&quot;`
}

I want to have a function that converts the TagList into string arrays (my own serialization function). So the function will look like this

func serialize(tagList &lt;?&gt;) string

What I should define as the type <?> is what I am not sure about. Because if I called this function using

serialize(mydata.TagList)  // mydata is the ds struct type

Then it will remind me that this type is []struct{...}

But I am not sure how to define the []struct{...}.

I am also open for existing serialization library apis i can use to do this as long as it serialized into a string.

答案1

得分: 1

推荐的方法是为嵌套的结构字段声明一个新类型,这样你就可以在需要的时候通过名称引用该类型;例如:

type Tag struct {
    Key   string `json:"Key"`
    Value string `json:"Value"`
}

type ds struct {
    name    string
    TagList []Tag `json:"TagList"`
}

// ...

func serialize(tagList []Tag) string {
    // ...
}

否则,如果不声明新类型,就必须在每个想要使用该类型的地方重复整个匿名结构的类型定义;例如:

func serialize(tagList []struct {
    Key   string `json:"Key"`
    Value string `json:"Value"`
}) string {
    // ...
}
英文:

The recommended approach is to declare a new type for the nested struct field so that you can reference the type by name whenever you need to; for example:

type Tag struct {
    Key   string `json:&quot;Key&quot;`
    Value string `json:&quot;Value&quot;`
}

type ds struct {
    name    string
    TagList []Tag `json:&quot;TagList&quot;`
}

// ...

func serialize(tagList []Tag) string {
    // ...
}

Otherwise, without declaring the new type, one would have to repeat the whole type definition of the anonymous struct in every place where one wants to use that type; for example:

func serialize(tagList []struct {
    Key   string `json:&quot;Key&quot;`
    Value string `json:&quot;Value&quot;`
}) string {
    // ...
}

huangapple
  • 本文由 发表于 2022年12月7日 13:48:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/74712288.html
匿名

发表评论

匿名网友

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

确定