如何定义嵌入/匿名字段(go struct)

huangapple go评论88阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年8月26日 01:17:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/25491053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定