extend a struct with multiple fields in go

To extend a struct with multiple fields in Go, we can use embedded structs. An embedded struct is a struct that is included as a field of another struct. By including the fields of the embedded struct in the parent struct, we can extend the parent struct with additional fields.

Here's an example:

main.go
type Person struct {
    Name string
    Age  int
}

type Employee struct {
    Person
    Salary float64
}

func main() {
    emp := Employee{
        Person: Person{
            Name: "John Doe",
            Age:  32,
        },
        Salary: 50000.0,
    }

    fmt.Println(emp.Name)    // Output: John Doe
    fmt.Println(emp.Age)     // Output: 32
    fmt.Println(emp.Salary)  // Output: 50000
}
403 chars
24 lines

In this example, we have a Person struct with two fields Name and Age. We also have an Employee struct that embeds Person and adds a field Salary. By including Person as a field of Employee, we've extended Employee with the fields of Person.

We can now create an instance of Employee and access its fields as we would access the fields of any other struct.

related categories

gistlibby LogSnag