Logo

Developer learning path

Go

Embedding Structs in Go

Embedding Structs

3

#description

In the Go programming language, structs are a composite data type that allows you to group together different types of data into a single object. Embedding is a powerful feature of Go structs that allows you to embed one struct type into another, creating a parent-child relationship between the two types.

There are two ways to embed structs in Go:

  1. Anonymous embedding: In anonymous embedding, you embed a struct directly into another struct without providing a name. This way, the fields of the embedded struct become part of the outer struct.

For example, let's say you have a struct called Person that has fields for name and age.

You can embed this Person struct into another struct called Employee as follows:

                    
type Person struct {
    name string
    age  int
}

type Employee struct {
    Person
    id   int
    role string
}
                  

In this example, the Employee struct is embedding the Person struct. This means that any Employee object will also have the fields name and age from the embedded Person struct, in addition to the id and role fields defined directly in the Employee struct.

  1. Named embedding: In named embedding, you embed a named struct type into another struct and give it a name, which becomes a field in the outer struct.

For example, let's say you have a struct called Address that has fields for street, city, and state.

You can embed this Address struct into another struct called Person as follows:

                    
type Address struct {
    street string
    city   string
    state  string
}

type Person struct {
    address Address
    name    string
    age     int
}
                  

In this case, the Person struct is embedding the Address struct, but it's a named embedding, so the Address struct is given the name address and becomes a field of the Person struct.

Embedding allows you to create complex object models by building relationships between types. It also allows you to inherit fields and methods from embedded types, making it a powerful feature that can help you write more concise, modular and reusable code.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.