DoIt
DoIt

Reputation: 3448

reusing structs in another struct in golang

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?

Upvotes: 1

Views: 3071

Answers (2)

poy
poy

Reputation: 10537

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"]}

Upvotes: 3

Kenny Grant
Kenny Grant

Reputation: 9633

Just use one struct - DataWithItems and sometimes leave items blank

Upvotes: 0

Related Questions