extend a struct with a field in go

To extend a struct with a new field in Go, you can use embedding. By embedding a struct within another struct, the fields of the embedded struct become part of the embedding struct.

main.go
type Person struct {
    name string
    age  int
}

type Employee struct {
    Person
    salary float64
}
108 chars
10 lines

In the above example, the Employee struct embeds the Person struct. This means that Employee struct now has all of the fields of the Person struct in addition to its own fields.

You can now create instances of the Employee struct and access the fields of the Person struct using dot notation:

main.go
employee := Employee{
    Person: Person{
        name: "John Smith",
        age:  30,
    },
    salary: 50000,
}

fmt.Println(employee.name)  // "John Smith"
fmt.Println(employee.age)   // 30
fmt.Println(employee.salary)  // 50000
234 chars
12 lines

In this way, you can extend a struct with a new field in Go by embedding another struct within it.

gistlibby LogSnag