skip to content
Alvin Lucillo

Embed a type in a struct in Go

/ 1 min read

💻 Tech

In Go, with composition, you can embed a type within a struct. This will automatically let the struct embed or “inherit” the methods of the embedded type. In addition, you can choose not to specify the field name in struct definition as Go will use the type name as the field name. Here’s an example:

type NewDate struct {
    time.Time
}

d := NewDate{Time: time.Now()} // you can omit Time but this produce a vet warning

fmt.Printf("%v %v", d, d.Minute()) // prints the date and the minute; d, a NewDate, has access to time.Time methods