// 定义一个接口,包含一个接收者为接口类型的方法,该方法返回接口自身以便于链式调用
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()
}
一个golang 基于 interface 链式调用的示例
摘要
// 定义一个接口,包含一个接收者为接口类型的方法,该方法返回接口自身以便于链式调用 type Chainable interface { DoSomething() Chainable DoSomething2() Chainable }
本文为本站原创,转载请注明出处。文中观点与所涉产品信息以官方发布为准。

