Home > Blockchain >  How to define a json struct type for function signature?
How to define a json struct type for function signature?

Time:12-08

I have a struct definition

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

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 <?>) 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.

CodePudding user response:

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:"Key"`
    Value string `json:"Value"`
}

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

// ...

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:"Key"`
    Value string `json:"Value"`
}) string {
    // ...
}
  • Related