英文:
Is there a spread operator for golang structs
问题
以下是翻译好的内容:
有以下的结构体,其中PostInput
是createPost
函数的参数。
type PostInput struct {
Title string
Content string
}
type PostInputWithTime struct {
Title string
Content string
CreatedAt time.Time
UpdatedAt time.Time
}
但是不希望将CreatedAt
和UpdatedAt
暴露给用户,所以我将它们添加到函数内部,如下所示。
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论