1

Hopefully this makes sense. I have a program I'm writing, which is all but finished and ready for testing, with one minor (major issue). In the Model package, the context is declared perfectly well, and the cancelFunc is accessible and can be called with a defer as normal:

CTX, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

However, when I try to call and use CTX from the main function, cancel is apparently an unresolved reference. CTX can be used perfectly well by calling Model.CTX, but I'm not sure what I'm doing wrong. This is the code that doesn't work:

Model.CTX, cancel = context.WithTimeout(context.Background(), 10*time.Second)
    cancel()

Apologies if this is a bad question, as always I'm open to suggestions to improve the quality of my questions.

Thankyou

  • 2
    Only the owner of the `cancel()` function holds the power and responsibility to cancel the context. If it is needed at other places, expose access to it or pass it where it's needed. See related: [Cancel context from child](https://stackoverflow.com/questions/66679577/cancel-context-from-child/66679667#66679667) – icza Apr 07 '22 at 10:04
  • You can also [merge two independent contexts](https://stackoverflow.com/a/58489004/1218512) into a single context - using that single context to propagate cancelation. – colm.anseo Apr 07 '22 at 15:06

0 Answers0