Database entities, retention and data mapping.
type User struct{
UserId int
Org int
Name string
Password string
Sex int
Age int
Avatar string
}
type Address struct{
AddressId int
UserId int
Province int
City int
District int
Address int
Description string
}
In DAO, I want to combine, cut, and expand the entity structure... for example:
type UserInfo struct{
User
[]Address
}
But the anonymous structure is embedded and can only be quoted in its entirety. How can I quote some fields?
type UserInfo struct{
User
[]Address
Password string `json:"-"`
Sex int `json:"-"`
Age int `json:"-"`
}
CodePudding user response:
You can't "quote" some fields. You may embed (or use a regular field) of User
, or if you don't need all its fields, just explicitly list the needed ones.
Don't be afraid to repeat 3 fields. Quoting Sandi Metz:
Duplication is far cheaper than the wrong abstraction.
If you need "too many" fields and you do want to avoid duplicates, you may put those fields into another struct, and have that embedded both in User
and in UserInfo
:
type BaseUser struct {
Password string `json:"-"`
Sex int `json:"-"`
Age int `json:"-"`
}
type User struct {
BaseUser
UserId int
Org int
Name string
Avatar string
}
type UserInfo struct {
BaseUser
Addresses []Address
}
Note that you may choose to use a struct tag when embedding BaseUser
to exclude it from JSON marshalling instead of marking all of BaseUser
's fields.
CodePudding user response:
You can try this
type UserInfo struct{
User
Addresses []Address
Password string `json:"-"`
Sex int `json:"-"`
Age int `json:"-"`
}