Context
针对场景
传递上下文
控制子goroutine的执行
超时控制的方法调用
可以取消的方法调用
基本用法
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key interface{}) interface{}
}
Deadline:返回Context被取消的截止日期,如果没有截止日期那么ok返回false
Done:返回一个Chan,Context被取消时这个Chan会被close
Err:Done没有被close,返回nil;Done被close,返回Done被close的原因
Value:返回Key对应的Value
Root Context可以直接使用context.BackGround创建
background = new(emptyCtx)
type emptyCtx int
func (*emptyCtx) Deadline() (deadline time.Time, ok bool) {
return
}
func (*emptyCtx) Done() <-chan struct{} {
return nil
}
func (*emptyCtx) Err() error {
return nil
}
func (*emptyCtx) Value(key interface{}) interface{} {
return nil
}
特殊用途
前提知识
当匿名字段是一个struct的时候,那么这个struct所拥有的全部字段以及方法(指绑定在这个类型上的,见最后)都被隐式地引入了当前定义的这个struct
WithValue
func WithValue(parent Context, key, val interface{}) Context {
if parent == nil {
panic("cannot create context from nil parent")
}
if key == nil {
panic("nil key")
}
if !reflectlite.TypeOf(key).Comparable() {
panic("key is not comparable")
}
return &valueCtx{parent, key