Golang Struct Anonymous Fileds
Golang anonymous struct field example .
Anonymous struct field and method and interface
What is anonymous field
First we can see an example:
package main
import "fmt"
type Animal struct {
Name string
Sex string //male or female
}
type Dog struct {
Animal
Kind string
}
type Husky struct {
Dog
Cute bool
}
func (d Dog) Greet() {
fmt.Printf("Hello, I'm a %s\n", d.Kind)
}
type Pet interface {
Greet()
}
func petGreet(p Pet) {
p.Greet()
}
func main() {
d := Dog{Animal: Animal{Name: "旺财", Sex: "male"}, Kind: "Husky"}
h := &Husky{Dog: d, Cute: true}
fmt.Println(h.Name)
fmt.Println(h.Dog.Name)
fmt.Println(h.Animal.Name)
fmt.Println(h.Dog.Animal.Name)
d.Greet()
h.Greet()
h.Dog.Greet()
petGreet(d)
petGreet(h)
}
Output would be:
旺财
旺财
旺财
旺财
Hello, I'm a Husky
Hello, I'm a Husky
Hello, I'm a Husky
Hello, I'm a Husky
Hello, I'm a Husky
We can conclude the features of anonymous filed, these should be the motivation or benefits for it.
- anonymous field is a struct field without specifing the field name.
- An anonymous field has an implicit name of the field type.
- We can access field and methods of Anonymous fileds using shortcut notation without the implicit filed name. Just like h.Greet() is equvalent to h.Dog.Greet()
- if the anonymous field implements or satisfys some interface, so does the whole struct