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

huangapple go评论94阅读模式
英文:

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

问题

问题听起来有点奇怪,但我不知道有什么更好的方式来表达。我正在使用goquery,并且我在一个switch-case语句中:

switch {
    case url == url1:
        doc.Find("xyz").Each(func(i int, s *goquery.Selection) {
            a, _ := s.Attr("href")
            if a == b {
                //我想要立即跳出switch-case。我不想要遍历所有的选择项。这是我想要的结果。
                break
            }
        })
}

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

在这里,我应该使用什么来跳出switch-case,而不是让程序遍历每个选择项并运行我的函数?

英文:

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?

答案1

得分: 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
        })
}

只要在你的switch case中没有剩余的代码,你就不需要使用break语句。

英文:

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.

huangapple
  • 本文由 发表于 2017年4月1日 19:46:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/43156455.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定