Does golang structure have spread operator?

PHPz
Release: 2024-02-09 12:36:19
forward
394 people have browsed it

golang 结构是否有扩展运算符

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.

Question content

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
}
Copy after login

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)
}
Copy after login

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
}
Copy after login

Solution

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!