How to Stop a Goroutine in Go

Goroutines cannot be forcibly stopped; they must be signaled via context or channels to exit gracefully.

Go does not provide a direct way to forcibly stop a running goroutine; you must signal it to exit gracefully using a context.Context or a chan struct{}. The goroutine must explicitly check for this signal and return from its function to terminate.

ctx, cancel := context.WithCancel(context.Background())

// Start the goroutine
go func() {
    for {
        select {
        case <-ctx.Done():
            fmt.Println("Goroutine stopped")
            return // Exit the function
        default:
            // Do work
        }
    }
}()

// Stop the goroutine later
cancel()