英文:
Can context.Context variables be copied and still function normally in all ways in golang?
问题
我看到以下情况:
func foo(ctx context.Context) {
localCtx := ctx
... //做一些事情
}
这两个 context.Context
变量在所有方面都可以互换使用吗?
从源代码来看,WithCancel
、WithDeadline
、WithTimeout
和 WithValue
返回的 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
变量实际上是指针,所以localCtx
和ctx
都指向同一个对象。
关于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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论