Why not put contexts in structs?

141 views
Skip to first unread message

john...@gmail.com

unread,
Sep 24, 2019, 10:43:00 PM9/24/19
to golang-nuts
I've read the documentation recommended never to store a context in a struct.  I'm curious to know why that's a bad thing.  Is it just because context is request-scoped, and the struct may not be?  Or is there more to it than that?  In other words, what can go wrong if you store a context in a struct?


(And what do we actually mean by request-scoped? Do we specifically mean "a chain of function calls" or do we mean something more conceptual, like a "request" received by a server?)

john...@gmail.com

unread,
Sep 24, 2019, 10:43:17 PM9/24/19
to golang-nuts

anderson...@blacklane.com

unread,
Sep 26, 2019, 3:15:14 PM9/26/19
to golang-nuts
Well, one of the reasons is convention. The context should be passes as paramter and be the first paramter as is stated in the package documentation.
For sure following the convention it's easier to know where the context came from, when it's available.
Inside a struct it's somehow hidden, might not obivious there is a context there, or end up being replaced rather than updated.

It's what I have in my mind.

Caleb Spare

unread,
Sep 26, 2019, 3:48:32 PM9/26/19
to john...@gmail.com, golang-nuts
You can read some more discussion about this recommendation at
https://github.com/golang/go/issues/22602. (That's where I propose
relaxing it somewhat, since I think the current phrasing is too
strict.)

On Tue, Sep 24, 2019 at 7:42 PM <john...@gmail.com> wrote:
>
> I've read the documentation recommended never to store a context in a struct. I'm curious to know why that's a bad thing. Is it just because context is request-scoped, and the struct may not be? Or is there more to it than that? In other words, what can go wrong if you store a context in a struct?
>
>
> (And what do we actually mean by request-scoped? Do we specifically mean "a chain of function calls" or do we mean something more conceptual, like a "request" received by a server?)
>
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/dad8b56c-add0-49bc-b53e-f4238f19ae4f%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages