欢迎访问 生活随笔!

生活随笔

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

编程问答

Go语言可能会遇到的坑

发布时间:2025/4/5 编程问答 48 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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语言可能会遇到的坑的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。