Blog    Bookmark    Note    Photo    Password Manager    About Me    Settings    Sign out



Tips using anonymous structs in Golang


You can embed a struct inside another one without giving it a name. For example,

type Foo struct {
    Bar
}

type Bar struct {
    ID string
}

The field Bar inside the Foo object is an anonymous struct because it has no name. By default, the name of the field Bar inside Foo is Bar.

You have two ways to access the fields of Bar from Foo. 

Foo.ID

or

Foo.Bar.ID

Then how to initialize the Foo object? Can you assign a value to ID by Foo.ID = "id"? No, even though we can reference ID in this way, the Foo doesn't have a field named ID! The right way to initialize Foo is as below.

foo:= Foo{
    Bar{
      ID: "id",
    }
}

Sometimes, there may have name conflict if there are multiple anonymous structs which have the fields with the same name. Say,

type Foo struct {
    Bar
    Moo
}

type Moo struct {
    ID string
    Name string
}


In such case, what does Foo.ID mean? It is a conflict. The compiler doesn't which ID it refers to. So you should explictly tell the compiler which object you want to refer to. 

Foo.Bar.ID
or
Foo.Moo.ID






  


Comments:

Write a comment
Anonymous

Captcha image

Reload

Type the number you see in the image above: