In the development of PHP, we often encounter the situation of using the fields of another structure in one structure. However, referencing it directly as a key can lead to cluttered and unmaintainable code. So how to use structure fields in another structure? PHP editor Baicao provides you with a concise and clear solution to make your code clearer and easier to read. Let’s take a look below!
I want to insert a structure field into another structure without having to use the structure name.
I know I can do this:
type person struct { name string } type user struct { person email, password string }
But it will produce this structure:
user := user{person: person{name: ""}, email: "", password: ""}
How can I do something like this:
type person struct { name string } type user struct { name person.name // here email, password string }
Use it like this
user := User{Name: "", Email: "", Password: ""}
is it possible?
Simply put, it cannot be done using the current language implementation.
When initializing a literal, you need to be explicit (or, in other words:literal![sic]). Sinceuser
containsperson
, the literaluser
must contain the literalperson
, as follows:
u := user{ person: person{ name: "bob", }, email: "[email protected]", password: "you're kidding right?", }
However, once you have avariable
of typeuser, you can leverage the anonymous field to set (or get) the anonymousperson# via
user## of
name:
u := user{} u.name = "bob" u.email = "[email protected]", u.password = "you're kidding right?",
personcould be initialized the way you are looking for:
u := user{ name: "bob" }
userstructure and
addits ownnamefield:
type user struct { person name string email string password string }
canobviously initialize the newnamefield:
u := user{ name: "bob" }
user.person.namebefore, but now it is initializing
user.name. not good.
namefield in
useralreadysimilarly "destroy" theuser
variable on the
name Unqualified reference to:
u.name = "bob" // used to set user.person.name, now sets user.name
personfields, the
user.person.namefield is marshaled by default to json as the "name" field:
{ "name": "", "email": "", "password": "" }
namefield is added,
thisis the field marshalled as"name", and
user.person.nameFields are not grouped at all
>.
jsontag to
user.person.name, like
type user struct { person `json:"personname"` name string email string password string }
nowpersonis marshaled into an
objectwith a
namefield:
{ "PersonName": { "Name": "" }, "Name": "", "Email": "", "Password": "" }
This can happen if you try to change the name of a marshaled field for an anonymousperson, even though
userdoes not have a
namefield
.
The above is the detailed content of How to use a struct field in another struct without referencing it as a key. For more information, please follow other related articles on the PHP Chinese website!