Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to exit a function with infinite loop of channel

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading