data structures - Understanding go nested structs -


i'm trying understand nested structs in go, made little test: (playground)

type struct {     string }  type b struct {         b string }  func main() {     b := b{a{"a val"}, "b val"}      fmt.printf("%t -> %v\n", b, b)   // b has nested , values      // main.b -> {{a val} b val}      fmt.println("b.b ->", b.b)       // b's own value     // b.b -> b val      fmt.println("b.a.a ->", b.a.a)   // b's nested value     // b.a -> val      fmt.println("b.a ->", b.a)       // b's nested value? or own value?     // b.a -> val } 

so how , why last 2 lines work? same? should use?

they same. see the go spec on selectors:

for value x of type t or *t t not pointer or interface type, x.f denotes field or method @ shallowest depth in t there such f. if there not 1 f shallowest depth, selector expression illegal.

note means b.a illegal if type b embeds 2 types same field on same depth:

type a1 struct{ string } type a2 struct{ string } type b struct {     a1     a2 }  // ... b := b{a1{"a1"}, a2{"a2"}} fmt.println(b.a) // error: ambiguous selector b.a 

playground: http://play.golang.org/p/ptqm-hzbdr.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -