英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论