Context:源码解读

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值