Is there a spread operator for golang structs

2.9k Views Asked by At

Have the following structs where PostInput is a param for a createPost function.

type PostInput struct {
  Title String
  Content String
}

type PostInputWithTime struct {
 Title String
 Content String
 CreatedAt Time
 UpdatedAt Time
}

But do not want CreatedAt and UpdatedAt to be exposed to users so i add it inside the function like so.

func createPost(input PostInput) {
  updatedInput = PostInputWithTime{
    Title: input.Title
    Content: input.Content
    CreatedAt: time.Now()
    UpdatedAt: time.Now()
  }
  db.InsertOne(updatedInput)
}

It is working fine but curious if there is a more elegant way to do it? I know it's possible to embed struct on another struct but not on the root layer (like javascript spread operator).

// something like this
type PostInputWithTime struct {
 ...PostInput
 CreatedAt
 UpdatedAt
}
2

There are 2 best solutions below

0
Volker On BEST ANSWER

Is there a spread operator for go[...] structs [...] like javascript spread operator [?]

No.

(You either have to use embedding, copy the values or implement some reflect-based magic, but no, no spread.)

0
rosmak On
type PostInput struct {
  Title string
  Content string
}

type PostInputWithTime struct {
 PostInput //Struct Embedding
 CreatedAt time.Time
 UpdatedAt time.Time
}