英文:
How to define embedded /anonymous fields (go struct )
问题
我正在尝试初始化一个嵌入式结构体。然而编译器报错说我不能混合使用值和值初始化器。正确的语法是什么?
httpCl的类型是*requests.Trans
type clTran struct {
*requests.Trans
uCh chan user
}
func main() {
httpCl, err := requests.tr(px)
clT := clTran{httpCl, uCh: uCh}
}
英文:
I'm trying to initialize an embedded struct. However the compiler says I can't mix values and and value initializers. What's the correct syntax ?
httpCl is of type *requests.Trans
type clTran struct {
*requests.Trans
uCh chan user
}
func main() {
httpCl, err := requests.tr(px)
clT := clTran{httpCl, uCh: uCh}
}
答案1
得分: 4
如果你在结构体字面量中标记字段(通常应该这样做),所有字段都需要标记。在嵌入的情况下,字段采用其类型的名称。所以
clT := clTran {
Trans: httpCl,
uCh: uCh,
}
请注意,该字段名称也适用于访问和写入操作,clT.Trans = httpCl
是有效的,并且将写入到嵌入字段中。
英文:
If you label fields in a struct literal (which you usually should) all of them need to be labeled. In the case of embedding, the field takes the name of its type. So
clT := clTran {
Trans: httpCl,
uCh: uCh,
}
Note that this field name applies to accessing and writing too, clT.Trans = httpCl
is valid and will write to the embedded field.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论