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

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

问题描述:

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}
}

我正在尝试初始化嵌入式结构。 但是,编译器说我不能混合使用值和和值初始化程序。 什么是正确的语法? httpCl的类型为 * requests.Trans code> p>

 类型clTran struct {
 * requests.Trans 
 uCh chan用户
} 
  
func main(){
 httpCl,err:= requests.tr(px)
 clT:= clTran {httpCl,uCh:uCh} 
} 
  code>  pre> 
  div  >

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.