日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Go语言可能会遇到的坑

發布時間:2025/4/5 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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循環,只是跳出了一次select
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 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语言可能会遇到的坑的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。