Welcome to our deep dive into Go Embedded Structs! In this lesson, we'll explore how to create and use structs in Go, and how to embed one struct within another to form complex data structures. Let's get started!
Structs (structures) in Go are user-defined data types that allow you to group related variables together. They consist of fields (variables) and methods (functions associated with the struct).
type Point struct {
X int
Y int
}In the example above, we've defined a new struct called Point with two fields: X and Y, both of type int.
Embedding one struct within another allows us to reuse code and create complex data structures. When a struct is embedded, the embedded struct becomes a part of the enclosing struct and inherits its fields and methods.
type Vector struct {
Point
Z int
}In the example above, we've defined a new struct called Vector that embeds the Point struct. Now, whenever we create a Vector, it will automatically have an X, Y, and Z field.
To access embedded fields, we use dot notation to navigate through the hierarchical structure.
v := Vector{Point{1, 2}, 3}
fmt.Println(v.X) // Output: 1
fmt.Println(v.Y) // Output: 2
fmt.Println(v.Z) // Output: 3In the example above, we've created a Vector instance called v with an embedded Point instance and an additional Z field. To access the embedded Point's fields, we use dot notation to navigate to them.
Anonymous embedding allows us to embed an entire struct without giving it a name. This can be useful when we want to reuse the embedded struct's behavior without explicitly defining it.
type Complex struct {
Real float64
Imag float64
}
type Vector3D struct {
Complex
X float64
Y float64
Z float64
}In the example above, we've embedded the Complex struct without giving it a name. This allows the Vector3D struct to have a Real and Imag field, inherited from the Complex struct.
What is the purpose of embedding one struct within another in Go?
That's it for our deep dive into Go Embedded Structs! In the next lesson, we'll explore Go Interfaces and how they can help you create flexible, extensible code. Stay tuned! 🌟