type A struct {
B struct {
Some string
Len int
}
}
简单的问题。如何初始化这个结构体?我想做这样的事情:
a := &A{B:{Some: "xxx", Len: 3}}
预计我会收到错误:
missing type in composite literal
当然,我可以创建一个单独的结构体 B 并以这种方式初始化它:
type Btype struct {
Some string
Len int
}
type A struct {
B Btype
}
a := &A{B:Btype{Some: "xxx", Len: 3}}
但它不如第一种方法有用。有没有初始化匿名结构的快捷方式?
The 可分配性规则 http://golang.org/ref/spec#Assignability对匿名类型是宽容的,这导致了另一种可能性,您可以保留原始定义A
同时允许写入该类型的短复合文字。如果您确实坚持使用匿名类型B
领域,我可能会写这样的内容:
package main
import "fmt"
type (
A struct {
B struct {
Some string
Len int
}
}
b struct {
Some string
Len int
}
)
func main() {
a := &A{b{"xxx", 3}}
fmt.Printf("%#v\n", a)
}
操场 http://play.golang.org/p/5tkQ4R98kJ
Output
&main.A{B:struct { Some string; Len int }{Some:"xxx", Len:3}}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)