具有以下结构,其中 postinput
是 createpost
函数的参数。
type postinput struct { title string content string } type postinputwithtime struct { title string content string createdat time updatedat 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 扩展运算符)。
// something like this type PostInputWithTime struct { ...PostInput CreatedAt UpdatedAt }
是否有像 javascript 扩展运算符 [...] 一样的 go[...] 结构 [...] 扩展运算符?
没有。
(您必须使用嵌入、复制值或实现一些基于反射的魔法,但不,没有传播。)