在Go语言中,context.Context变量可以被复制并在所有方面正常工作吗?

huangapple go评论71阅读模式
英文:

Can context.Context variables be copied and still function normally in all ways in golang?

问题

我看到以下情况:

func foo(ctx context.Context) {
    localCtx := ctx 
    ... //做一些事情
}

这两个 context.Context 变量在所有方面都可以互换使用吗?

从源代码来看,WithCancelWithDeadlineWithTimeoutWithValue 返回的 context.Context 变量在内部实际上是指向结构体的指针,这使我认为如果父上下文来自这些函数之一,它们可以互换使用。然而,context.Background() 返回的 emptyCtx 在内部是一个整数,所以我在这里想也许如果父上下文是背景上下文,它们就不能在内部使用。

但是,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.

答案1

得分: 11

是的,你可以互换使用它们。

正如你已经注意到的那样,WithCancel等函数返回的context变量实际上是指针,所以localCtxctx都指向同一个对象。

关于emptyCtx是一个int类型,这不会改变任何事情,因为它也被用作指针。

你提到的background变量实际上是指向一个emptyCtx的指针,它是通过使用new关键字进行初始化的:

background = new(emptyCtx)
英文:

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)

答案2

得分: 0

context.Context 是一个接口。它的大小为两个指针。复制最多16个字节一点都不可怕。

英文:

context.Context is an interface. Its size is two pointers. Copying up to 16 bytes is not scary at all

huangapple
  • 本文由 发表于 2017年8月23日 01:17:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/45823531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定