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.
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)
context.Context
is an interface. Its size is two pointers. Copying up to 16 bytes is not scary at all