1

I have two structs in golang as below

type Data struct {
    Name          string
    Description   string
    HasMore   bool
}

type DataWithItems struct {
    Name          string
    Description   string
    HasMore      bool
    Items    []Items
}

At most DataWithItems struct can be rewritten as

 type DataWithItems struct {
        Info Data
        Items []Items
    }

But the above make it difficult when decoding a json object into DataWithItems. I know this can be solved with inheritance in other programming languages but Is there a way I can solve this in Go?

2 Answers 2

3

You can "embed" the one struct into the other:

type Items string

type Data struct {
    Name        string
    Description string
    HasMore     bool
}

type DataWithItems struct {
    Data // Notice that this is just the type name
    Items []Items
}

func main() {
    d := DataWithItems{}
    d.Data.Name = "some-name"
    d.Data.Description = "some-description"
    d.Data.HasMore = true
    d.Items = []Items{"some-item-1", "some-item-2"}

    result, err := json.Marshal(d)
    if err != nil {
        panic(err)
    }

    println(string(result))
}

this prints

{"Name":"some-name","Description":"some-description","HasMore":true,"Items":["some-item-1","some-item-2"]}
Sign up to request clarification or add additional context in comments.

2 Comments

You can also reference the fields of Data in DataWithItems directly as long as there are no name conflicts. For example d.Name works.
@HenryWoody Very true! I can never tell which I prefer for readability.
0

Just use one struct - DataWithItems and sometimes leave items blank

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.