php editor Xigua will discuss a question about the Golang language in this article: whether there is an expansion operator for structures. As a modern programming language, Golang has many powerful features and functions, but in some specific scenarios, developers may encounter the need to extend the structure. This article will introduce in detail the knowledge related to structure expansion in Golang and give solutions. If you are interested in Golang’s structural spread operator, then please continue reading this article.
has the following structure, where postinput
is the parameter of the createpost
function.
type postinput struct { title string content string } type postinputwithtime struct { title string content string createdat time updatedat time }
But don't want createdat
and updatedat
to be exposed to the user, so I added it to the function as shown below.
func createpost(input postinput) { updatedinput = postinputwithtime{ title: input.title content: input.content createdat: time.now() updatedat: time.now() } db.insertone(updatedinput) }
It works fine, but was curious if there is a more elegant way to do this? I know it's possible to embed a struct on top of another struct, but not on the root level (like the javascript spread operator).
// something like this type PostInputWithTime struct { ...PostInput CreatedAt UpdatedAt }
Is there a go[...] structure [...] spread operator like the javascript spread operator [...]?
No.
(You'd have to use embedding, copying values, or implementing some reflection-based magic, but no, there's no propagation.)
The above is the detailed content of Does golang structure have spread operator?. For more information, please follow other related articles on the PHP Chinese website!