Go语言可能会遇到的坑
生活随笔
收集整理的這篇文章主要介紹了
Go语言可能会遇到的坑
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近在用go開發項目的過程中突然發現一個坑,尤其是對于其它傳統語言轉來的人來說一不注意就掉坑里了,話不多說,咱看代碼:
1//writeToCSV2func writeESDateToCSV(totalValues chan []string) {3 f, err := os.Create("t_data_from_es.csv")4 defer f.Close()5 if err != nil {6 panic(err)7 }89 w := csv.NewWriter(f) 10 w.Write(columns) 11 12 for { 13 select { 14 case row := <- totalValues: 15 //fmt.Printf("Write Count:%d log:%s\n",i, row) 16 w.Write(row) 17 case <- isSendEnd: 18 if len(totalValues) == 0 { 19 fmt.Println("------------------Write End-----------------") 20 break 21 } 22 } 23 } 24 25 w.Flush() 26 fmt.Println("-------------------------處理完畢-------------------------") 27 isWriteEnd <- true 28} 當數據發送完畢,即isSendEnd不阻塞,且totalValues里沒數據時,跳出for循環,這里用了break。但是調試的時候發現,程序阻塞在了14行,即兩個channel都阻塞了。然后才驚覺這里break不是這么玩,然后寫了個測試方法測試一下:package mainimport ("time""fmt" )func main() {i := 0for {select {case <-time.After(time.Second * time.Duration(2)):i++if i == 5{fmt.Println("break now")break}fmt.Println("inside the select: ")}fmt.Println("inside the for: ")}fmt.Println("outside the for: ") } 運行輸出如下結果,break now之后還是會繼續無限循環,不會跳出for循環,只是跳出了一次selectinside the select: inside the for: inside the select: inside the for: inside the select: inside the for: inside the select: inside the for: break now inside the for: inside the select: inside the for: inside the select: inside the for: inside the select: inside the for:
若要break出來,這里需要加一個標簽,使用goto, 或者break 到具體的位置。
解決方法一:
使用golang中break的特性,在外層for加一個標簽:
package mainimport ("time""fmt" )func main() {i := 0endLoop:for {select {case <-time.After(time.Second * time.Duration(2)):i++if i == 5{fmt.Println("break now")break endLoop}fmt.Println("inside the select: ")}fmt.Println("inside the for: ")}fmt.Println("outside the for: ") }解決方法二:?
使用goto直接跳出循環:
package mainimport ("time""fmt" )func main() {i := 0for {select {case <-time.After(time.Second * time.Duration(2)):i++if i == 5{fmt.Println("break now")goto endLoop}fmt.Println("inside the select: ")}fmt.Println("inside the for: ")}endLoop:fmt.Println("outside the for: ") } 兩程序運行輸出如下:inside the select: inside the for: inside the select: inside the for: inside the select: inside the for: inside the select: inside the for: break now outside the for: Process finished with exit code 0綜上可以得出:go語言的switch-case和select-case都是不需要break的,但是加上break也只是跳出本次switch或select,并不會跳出for循環。
原文發布時間為:2018-09-16 本文作者:小碗湯 本文來自云棲社區合作伙伴“我的小碗湯”,了解相關信息可以關注“我的小碗湯”。
總結
以上是生活随笔為你收集整理的Go语言可能会遇到的坑的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PYTHON系列-从零开始的爬虫入门指南
- 下一篇: 【对讲机的那点事】节日出游对讲机选择你了