Context包
1 min read
在Go 1.7中,context包被引入到标准库中。 context是处理并发问题的一个标准风格。
context包内容很简单:
var Canceled = errors.New("context canceled")
var DeadlineExceeded error = deadlineExceededError{}
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
type CancelFunc func()
type Context interface{ ... }
func Background() Context
func TODO() Context
func WithValue(parent Context, key, val interface{}) Context
在使用context包的过程中,不应该Context存储在struct中,而是将Context作为参数传递给需要它的函数。不能传递nil Context,如果不确定该使用什么样的Context,那么传递context.TODO。
Last updated on 2019-07-17