How to exit a function with infinite loop of channel

Issue

I have this function that listens to RabbitMQ to consume a message.
And at some point, I want to stop listening and close the channel and quit the function.

func WaitForConfirm(expectedLen int){
    count := 0
    forever := make(chan bool)

    go func() {
        for i := 0; i < 5; i++ {
            count++
            if count == expectedLen {
                // HERE I WANT TO EXIT THE FUNCTION COMPLETELY
            }
        }
    }()

    <-forever
}

Oh, btw, I call this function like this:

go WaitForConfirm(2)

So, how can I stop the infinite loop and exit the function?

Solution

Actually, there is no infinite loop in your code and just chan is blocking your code.

You should send value to chan to release execution.

Here Example: https://go.dev/play/p/ujJjwBBsiP0

Answered By – Rasit aydin

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.