Go by Example: Struct Embedding

In Go, you can use struct embedding to create a new struct that includes all the fields and methods of an existing struct. Here’s an example that demonstrates how this works:

package main

import "fmt"

type Person struct {
    Name string
    Age int
}

func (p Person) Greet() {
    fmt.Println("Hello, my name is", p.Name)
}

type Student struct {
    Person
    Course string
}

func main() {
    s := Student{
        Person: Person{
            Name: "John Doe",
            Age: 20,
        },
        Course: "Computer Science",
    }

    s.Greet()
    fmt.Println("I am studying", s.Course)
}

In this example, we define a struct Person that has two fields, Name and Age, and a method, Greet. We then define a struct Student that embeds a Person struct.

When you embed a struct, you inherit all its fields and methods, so the Student struct has access to the Name, Age, and Greet methods of the Person struct.

In the main function, we create an instance of the Student struct, and call the Greet method and access the Course field.

The output of this program will be:

Hello, my name is John Doe
I am studying Computer Science

As you can see, struct embedding allows you to create new structs that inherit the fields and methods of other structs, without having to copy and paste the code. This is a powerful mechanism that allows you to create composite types that are made up of multiple parts.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *