如何从golang中的switch case中定义的函数内部中断开关案例?

时间:2017-04-01 11:46:21

标签: go switch-statement goquery

这个问题听起来很奇怪,但我还不知道有什么更好的方法。我正在使用goquery而且我在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
            }
        })
}

使用break会出现以下错误: break is not in a loop

我应该在这里使用什么来突破switch-case而不是让程序迭代每个选择并在每个选项上运行我的函数?

1 个答案:

答案 0 :(得分:2)

你应该使用goquery的EachWithBreak方法来停止迭代选择:

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

只要您的交换机案例中没有剩余代码,您就不需要使用break