一. 关于deadline函数返回的布尔值OK
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
deadTime, ok := ctx.Deadline()
其中的OK指的是当前的ctx是否设置了过期时间,所以上面的代码中ok是true,返回dateTime变量是ctx的到期时间
ctx, cancel := context.Background()
deadTime, ok := ctx.Deadline()
这里的OK则返回false,因为并没有过期时间
二. 当contex作为指针被传时,获取context的value时要这么写
func TestHutest(t *testing.T) {
ctx := context.Background()
ctx = context.WithValue(ctx, "t1", "bbbbb")
aa(&ctx)
fmt.Println(ctx.Value("hutest").(string))
//fmt.Println(ctx.Value("hutest222").(string))
}
func aa(ctx *context.Context) {
t1 := (*ctx).Value("t1")
t1String := (*ctx).Value("t1").(string)
fmt.Println(t1) //结果为bbbbb
fmt.Println(t1String )//结果为bbbbb
t2 := (*ctx).Value("t2")
t2String := (*ctx).Value("t2").(string)
fmt.Println(t2) //结果为nil
fmt.Println(t2String )//结果为panic
*ctx = context.WithValue(*ctx, "hutest", "aaaaaa") //此处相当于给aa函数外的父的ctx复制
}
只所有 (*ctx).Value(“t2”).(string)会panic,是因为此时key不存在,为nil,所有转.(string)就相当于吧nil去转了。
context.WithValue时会生成新的context,子并不会改变父context的值