In Go, you can initialize and work with embedded structs by simply declaring them as fields within a struct type. Essentially, an embedded struct is a field of any type, including a struct type.
Here's an example to demonstrate the initialization and usage of embedded structs in Go:
package main
import "fmt"
// Define a person struct
type Person struct {
Name string
Age int
}
// Define an employee struct that embeds the Person struct
type Employee struct {
Person // Embedded struct
EmployeeID int
Designation string
}
func main() {
// Initializing an embedded struct
emp := Employee{
Person: Person{
Name: "John Wick",
Age: 35,
},
EmployeeID: 12345,
Designation: "Software Engineer",
}
// Accessing embedded struct fields
fmt.Println("Employee Name:", emp.Name)
fmt.Println("Employee Age:", emp.Age)
fmt.Println("Employee ID:", emp.EmployeeID)
fmt.Println("Employee Designation:", emp.Designation)
// Updating embedded struct fields
emp.Name = "Jane Doe"
emp.Age = 30
fmt.Println("Updated Employee Name:", emp.Name)
fmt.Println("Updated Employee Age:", emp.Age)
}
In this example, we define a Person
struct with Name
and Age
fields. Then, we define an Employee
struct that embeds the Person
struct. The Employee
struct also has additional fields such as EmployeeID
and Designation
.
To initialize an embedded struct, you can assign a value to it along with other fields while creating an instance of the outer struct. In the main
function, we create an emp
instance of the Employee
struct, initialize the embedded Person
struct, and set values for other fields.
You can access the embedded struct's fields directly from the outer struct using dot notation. In this example, we print the values of emp.Name
, emp.Age
, emp.EmployeeID
, and emp.Designation
.
You can also update the embedded struct's fields by assigning new values to them. In the code above, we update emp.Name
and emp.Age
to "Jane Doe" and 30, respectively.
That's it! You now know how to initialize and work with embedded structs in Go.