gostructembedoperator-keywordspread

Is there a spread operator for golang structs


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
}

Solution

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