-2

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
}
gsmig
  • 80
  • 2
  • 10

2 Answers2

1

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

Volker
  • 40,468
  • 7
  • 81
  • 87
0
type PostInput struct {
  Title string
  Content string
}

type PostInputWithTime struct {
 PostInput //Struct Embedding
 CreatedAt time.Time
 UpdatedAt time.Time
}
rosmak
  • 545
  • 1
  • 12