extend a struct in go

In Go, you can extend an existing struct by embedding it into a new struct. This can be useful when you want to add additional fields or methods to the original struct.

Here is an example of how to extend a struct in Go:

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

type Employee struct {
    Person
    Salary float64
    Department string
}

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

    fmt.Println(emp.Name)
    fmt.Println(emp.Age)
    fmt.Println(emp.Salary)
    fmt.Println(emp.Department)
}
388 chars
24 lines

In this example, we have a Person struct with Name and Age fields. We then define a new struct Employee which embeds the Person struct and adds two new fields (Salary and Department).

You can create an instance of the Employee struct just like any other struct, and you can access the fields of both the Person and Employee structs.

related categories

gistlibby LogSnag