In Go, method chaining can be achieved using embedding, where a struct is embedded into another struct to inherit its fields and methods.
Here's an example of how to implement method chaining using embedding in Go:
package main
import "fmt"
type Person struct {
name string
age int
email string
}
func (p *Person) SetName(name string) *Person {
p.name = name
return p
}
func (p *Person) SetAge(age int) *Person {
p.age = age
return p
}
func (p *Person) SetEmail(email string) *Person {
p.email = email
return p
}
func (p *Person) Print() {
fmt.Printf("Name: %s, Age: %d, Email: %s\n", p.name, p.age, p.email)
}
type Employee struct {
Person
employeeID string
}
func main() {
emp := &Employee{}
emp.SetName("John").SetAge(30).SetEmail("[email protected]").Print()
// Output: Name: John, Age: 30, Email: [email protected]
}
In the example above, we have a Person
struct with fields for name
, age
, and email
, and methods SetName
, SetAge
, SetEmail
, and Print
. These methods return a pointer to Person
to allow method chaining.
We then define an Employee
struct that embeds the Person
struct. This allows the Employee
struct to inherit the fields and methods of Person
.
In the main
function, we create a new Employee
instance and use method chaining to set its name, age, email, and then print the details.
Note that embedding adds an "is-a" relationship between the embedded struct and the embedding struct, where the embedding struct "is a" type of the embedded struct. In the example, an Employee
"is a" Person
.