Go by Example: Embed Directive

The Go embed directive allows embedding of one struct type into another. The fields and methods of the embedded type become part of the outer type and can be accessed directly without a dot notation prefix. Here’s an example:

type Person struct {
  Name string
}

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

type Developer struct {
  Person
  Skills []string
}

func main() {
  dev := Developer{
    Person: Person{
      Name: "John Doe",
    },
    Skills: []string{"Go", "JavaScript", "Python"},
  }

  dev.Greet()
  fmt.Println("Skills:", dev.Skills)
}

In this example, the Person struct is embedded in the Developer struct, and the Person.Greet method can be called on a value of type Developer.


Comments

Leave a Reply

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