goswitch-statementgoquery

How to break out of switch case from inside a function defined inside the switch case in golang?


The question sounds weird but I didn't know any better way to put it. I am using goquery and I am inside a switch-case:

switch{
    case url == url1:
        doc.Find("xyz").Each(func(i int,s *goquery.Selection){
            a,_ := s.Attr("href")
            if a== b{
                //I want to break out of the switch case right now. I dont want to iterate through all the selections. This is the value.
                break
            }
        })
}

Using break gives the following error: break is not in a loop

What should I use here to break out of the switch-case instead of letting the program iterate over each of the selections and run my function over each of them?


Solution

  • You should make use of goquery's EachWithBreak method to stop iterating over the selection:

    switch {
        case url == url1:
            doc.Find("xyz").EachWithBreak(func(i int,s *goquery.Selection) bool {
                a,_ := s.Attr("href")
                return a != b
            })
    }
    

    As long as there's no remaining code in your switch case, you do not need to use a break.