Colleen Larsen
Colleen Larsen

Reputation: 733

Go : How to reference a field in an inherited struct

I have 2 structs whereby one inherits values that are common amongst all stucts denoted by type Common struct {...}

type Common struct{
    Id int
    CreatedAt time.Time
    UpdatedAt time.Time
    CreatorId int
}

type Post struct{
  type Post struct{
  Common
  Status
  Title string
  ShortDescription string
  Content string
  CategoryIds []int
  TagIds []int
  Url string
  MainImageId int
  Keywords []string
}

However when I try to create a new instance of the Post struct as in the following.

post1 := &Post{
    CreatorId:   1,
    Status: 1,
    Title: "this is the title of the first post",
    ShortDescription: "this is the short description of this post",
    Content: "",
    Url: "first-post",
    MainImageId: 1,
}

It does not recognise the CreatorId field. How would I reference this field in the new instance or modify the struct so that it registers CreatorID as part of the Post struct? Thanks

Upvotes: 0

Views: 152

Answers (1)

Ainar-G
Ainar-G

Reputation: 36189

CreatorId (which, by the way should be called CreatorID) is a part of Сommon, so the only way to initialize it in struct literal is:

post1 := &Post{
    Common: Common{CreatorID: 1},
    // ...
}

Alternatively,

post1 := &Post{
    // ...
}
post1.CreatorID = 1

Upvotes: 4

Related Questions