Is there a spread operator for golang structs

huangapple go评论68阅读模式
英文:

Is there a spread operator for golang structs

问题

以下是翻译好的内容:

有以下的结构体,其中PostInputcreatePost函数的参数。

type PostInput struct {
  Title string
  Content string
}

type PostInputWithTime struct {
 Title string
 Content string
 CreatedAt time.Time
 UpdatedAt time.Time
}

但是不希望将CreatedAtUpdatedAt暴露给用户,所以我将它们添加到函数内部,如下所示。

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

这样做是可以的,但我想知道是否有更优雅的方法?我知道可以在一个结构体中嵌入另一个结构体,但不能在根层级上嵌入(类似于JavaScript的扩展运算符)。

// 类似于这样
type PostInputWithTime struct {
 ...PostInput
 CreatedAt
 UpdatedAt
}
英文:

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
}

答案1

得分: 1

在Go语言中,没有像JavaScript中的spread操作符一样的用于结构体的spread操作符。你可以使用嵌入、复制数值或者实现一些基于反射的魔法来达到类似的效果,但是没有直接的spread操作符可用。

英文:

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

答案2

得分: 0

type PostInput struct {
  Title string
  Content string
}

type PostInputWithTime struct {
 PostInput //结构体嵌入
 CreatedAt time.Time
 UpdatedAt time.Time
}
type PostInput struct {
  Title string
  Content string
}

type PostInputWithTime struct {
 PostInput //Struct Embedding
 CreatedAt time.Time
 UpdatedAt time.Time
}
英文:
type PostInput struct {
  Title string
  Content string
}

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

huangapple
  • 本文由 发表于 2023年3月15日 22:26:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75746090.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定