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()