go select case的一个小坑

业务背景

image

之前在写很多if else时,对于不符合的分支条件总是习惯提前返回,减少对后面分支的心智负担,
最近在写1个go项目时,对于比较少使用go,在for select结构里遇到错误返回,导致直接返回了,后续tick就无效了

代码抽离简化如下

func Consumer() {
	tick := time.NewTicker(time.Duration(1000) * time.Millisecond)
	defer tick.Stop()
	n := 0
	for {
		select {
		case <-tick.C:
			msg := fmt.Sprintf("ticked:%s,n=%d", gtime.Now().String(), n)
			fmt.Println(msg)
			time.Sleep(2 * time.Second)
			n++
			//这里模拟出错,
			if n == 3 {
				fmt.Println(n)
				return
			}
			//后续处理
			//很多代码
		}

	}
	fmt.Println("end")
}

func TestConsume(t *testing.T) {
	go Consumer()
	time.Sleep(20 * time.Second)
}

代码执行到return 后,整个就返回了,后续的tick再也不起作用了,导致我的gqueue不能正常消费

posted @ 2024-08-03 17:18  H&K  阅读(5)  评论(0编辑  收藏  举报