This tutorial aims to help you understand how to work with embedded structs in Go. By the end of this tutorial, you should be able to:
Prerequisites:
You should have a basic understanding of Go programming, including how to define and use structs.
In Go, structs can contain other structs, and this concept is known as embedding. The idea behind this is instead of having a struct field with a name and type, you just specify the type. The struct you embed becomes a field of the struct it's included in, but without an explicit field name.
Best Practices:
- Use embedding for 'is-a' relationship, not 'has-a' relationship.
- Avoid embedding if it complicates your code. It should simplify and make your code more organized.
Example 1: Basic Example of Embedded Structs
package main
import "fmt"
// Defining a struct type
type Animal struct {
Name string
Age int
}
// Another struct type with Animal as embedded field
type Dog struct {
Breed string
Animal
}
func main() {
// Initializing Dog struct
d := Dog{
Breed: "Labrador",
Animal: Animal{
Name: "Max",
Age: 5,
},
}
fmt.Println(d)
}
In this example, Dog
struct embeds the Animal
struct. So, the Animal
struct becomes a field in the Dog
struct. The output of this program will be:
{Labrador {Max 5}}
Example 2: Accessing Fields of Embedded Structs
package main
import "fmt"
// Defining a struct type
type Animal struct {
Name string
Age int
}
// Another struct type with Animal as embedded field
type Dog struct {
Breed string
Animal
}
func main() {
// Initializing Dog struct
d := Dog{
Breed: "Labrador",
Animal: Animal{
Name: "Max",
Age: 5,
},
}
fmt.Println(d.Name)
fmt.Println(d.Age)
fmt.Println(d.Breed)
}
In this example, we access fields of the Animal
struct directly from a Dog
struct instance. The output will be:
Max
5
Labrador
In this tutorial, we have learned about embedded structs in Go. We've seen how to define them, how to create instances of structs with embedded structs, and how to access fields of embedded structs directly. Next, you can explore how to use embedded structs with interfaces for polymorphism.
Additional Resources:
- Go Documentation
- Effective Go
Exercise 1: Define a Circle
struct that embeds a Point
struct (with X
and Y
fields) and also has a Radius
field. Create an instance of Circle
, initialize it, and print its data.
Exercise 2: Extend the previous exercise by adding a method Area()
to the Circle
struct that calculates and returns the area of the circle. Print the area of the circle you created.
Solutions and explanations will be provided upon request.
Tips for Further Practice: Try to implement more complex programs using embedded structs. You can also explore the use of embedded interfaces in Go.