我最近在研究 golang 上下文,发现它WithCancel()以一种有趣的方式实现。
func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
if parent == nil {
panic("cannot create context from nil parent")
}
c := newCancelCtx(parent)
propagateCancel(parent, &c)
return &c, func() { c.cancel(true, Canceled) }
}
WithCancel()返回一个 ctx,以及一个取消相同上下文的函数。为什么这样做而不是引入.Cancel()类型本身的函数,比如
func (c *cancelCtx) Cancel() {
c.cancel(true, Canceled)
}
我了解使用 func 返回类型允许您根据运行时条件运行不同的 func,但这里没有动态 - 它始终是相同的 func。这仅仅是因为功能范式吗?
参考:https ://cs.opensource.google/go/go/+/master:src/context/context.go;l=232-239?q=context&ss=go%2Fgo
四季花海
相关分类