Golang nested struct

Jimmy (xiaoke) Shen
1 min readSep 22, 2020

--

Very interesting, for Golang nested struct, we can directly visit the lower level struct’s field.

An example can be found in the go playground

The code is here

package mainimport "fmt"// This `person` struct type has `name` and `age` fields.
type person struct {
name string
age int
}
type personNew struct {
person
address string
}
func main() {
fmt.Println(person{"Bob", 20})
personNew := personNew{person{"Jimmy", 40}, "staten island"}
fmt.Println(personNew)
fmt.Println(personNew.person.age)
// output here is same as above
fmt.Println(personNew.age)
}

Output

{Bob 20}
{{Jimmy 40} staten island}
40
40

--

--

No responses yet