doulin9679 2017-08-22 17:17
浏览 1213
已采纳

可以在golang中复制context.Context变量并以各种方式正常运行吗?

I'm seeing the following situation:

func foo(ctx context.Context) {
    localCtx := ctx 
    ... //do stuff
}

Can both of these context.Context variables be used interchangeably in all ways?

Looking at the source I see that the returned context.Context variables from WithCancel, WithDeadline, WithTimeout, and WithValue returned are implemented internally by a pointers to structs, which would make me think that yes, they could be used interchangeably if the parent context came from one of these functions. However, the emptyCtx returned by context.Background() is an int internally, so here I'm thinking perhaps they could not be used internally if the parent context was the background context.

But context.Context is actually an interface and I'm not sure if/how that changes things.

  • 写回答

2条回答 默认 最新

  • dongwen9947 2017-08-22 17:30
    关注

    Yes, you can use them interchangeably.

    As you already noticed, the context variables returned by WithCancel, etc, are actually pointers, so both localCtx and ctx will be pointing to the same thing.

    About emptyCtx being an int, it should not change things as it is also being used as a pointer.

    The background variable you mention is actually a pointer to an emptyCtx, as it is initialized by using the new keyword:

    background = new(emptyCtx)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算