英文:
Golang language, combine some fields of anonymous structure?
问题
数据库实体、保留和数据映射。
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
}
在DAO中,我想要组合、切割和扩展实体结构...
例如:
type UserInfo struct{
User
[]Address
}
但是匿名结构体只能作为整体引用,无法引用其中的某些字段。我该如何引用某些字段?
type UserInfo struct{
User
[]Address
Password string `json:"-"`
Sex int `json:"-"`
Age int `json:"-"`
}
英文:
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:"-"`
}
答案1
得分: 2
你不能“引用”某些字段。你可以嵌入(或使用普通字段)User
的字段,或者如果你不需要它的所有字段,只需明确列出所需的字段。
不要害怕重复3个字段。引用 Sandi Metz 的话:
重复比错误的抽象要便宜得多。
如果你需要“太多”字段,并且确实想避免重复,你可以将这些字段放入另一个结构体中,并将其同时嵌入到User
和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
}
请注意,你可以选择在嵌入BaseUser
时使用结构体标签,以将其排除在JSON编组之外,而不是标记BaseUser
的所有字段。
英文:
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.
答案2
得分: 1
你可以尝试这样做:
type UserInfo struct {
User
Addresses []Address
Password string `json:"-"`
Sex int `json:"-"`
Age int `json:"-"`
}
这段代码定义了一个名为UserInfo
的结构体,它包含了一个User
类型的字段和一个Address
类型的切片字段。此外,UserInfo
还有一个Password
字段,但在JSON序列化时会被忽略,即不会被包含在生成的JSON中。同样地,Sex
和Age
字段也会被忽略。
英文:
You can try this
type UserInfo struct{
User
Addresses []Address
Password string `json:"-"`
Sex int `json:"-"`
Age int `json:"-"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论