Search⌘ K
AI Features

Anonymous Fields and Embedded Structs

Explore the concept of anonymous fields and embedded structs in Go to understand how they enable composition and simulate inheritance. Learn how to assign values, manage naming conflicts, and compare structs, enhancing your struct manipulation skills in Go programming.

Definition

Sometimes, it can be useful to have structs that contain one or more anonymous (or embedded) fields that are fields with no explicit name. Only the type of such a field is mandatory, and the type is then also the field’s name. Such an anonymous field can also be itself a struct, which means structs can contain embedded structs. This compares vaguely to the concept of inheritance in OO-languages, and as we will see, it can be used to simulate a behavior very much like inheritance. This is obtained by embedding or composition. Therefore, we can say that in Go composition is favored over inheritance.

Consider the following program:

Go (1.6.2)
package main
import "fmt"
type innerS struct {
in1 int
in2 int
}
type outerS struct {
b int
c float32
int // anonymous field
innerS // anonymous field
}
func main() {
outer := new(outerS)
outer.b = 6
outer.c = 7.5
outer.int = 60
outer.in1 = 5
outer.in2 = 10
fmt.Printf("outer.b is: %d\n", outer.b)
fmt.Printf("outer.c is: %f\n", outer.c)
fmt.Printf("outer.int is: %d\n", outer.int)
fmt.Printf("outer.in1 is: %d\n", outer.in1)
fmt.Printf("outer.in2 is: %d\n", outer.in2)
// with a struct-literal:
outer2 := outerS{6, 7.5, 60, innerS{5, 10}}
fmt.Println("outer2 is: ", outer2)
}

In the above code, at line 4, we make a struct of type innerS containing two integer fields in1 and in2. At line 9, we make another struct of type outerS with two fields b (an integer) and c ...