2017-04-01 31 views
1

這個問題聽起來很奇怪,但我不知道有什麼更好的方式來表達它。我使用goquery,我裏面switch-case:使用break如何從golang中開關盒內定義的功能內部跳出開關盒?

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 is not in a loop

我應該用什麼在這裏打出來的開關情況,而不是讓程序迭代的在每個選擇上運行我的功能,通過每個選項?

+0

goto是你的朋友 –

回答

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