共计 369 个字符,预计需要花费 1 分钟才能阅读完成。
// 定义一个接口,包含一个接收者为接口类型的方法,该方法返回接口自身以便于链式调用
type Chainable interface {
DoSomething() Chainable
DoSomething2() Chainable
}
// 假设我们有两个不同的结构体,它们各自实现了Chainable接口
type Step1 struct{}
func (s *Step1) DoSomething() Chainable {
fmt.Println("执行 Step1 的操作")
return s
}
func (s *Step1) DoSomething2() Chainable {
fmt.Println("执行 Step2 的操作")
return s
}
func main() {
// 开始链式调用
chain := &Step1{}
chain.DoSomething().DoSomething2()
}
正文完