func main() { ctx := context.WithValue(context.Background(), key, value) // Pass the context to other functions or goroutines that need to access the shared value } // In other function or goroutine func doSomethingWithContext(ctx context.Context) { // Access the shared value val := ctx.Value(key) }
func main() { ctx, cancel := context.WithCancel(context.Background()) // Start a long-running task in a goroutine go func() { for { select { case <-ctx.Done(): // The context has been cancelled, so stop the task return default: // Do some work } } }() // Cancel the context when the user wants to stop the task cancel() }In both cases, the "context" package is used to pass data between functions or goroutines. The first example shows how to share a value between functions, and the second example shows how to cancel a long-running task.