Go 语言中Select与for结合使用时可能会遇到的坑

本文探讨了在Go语言中,当`for`循环与`select`结合使用时可能导致死循环的问题。文章提供了两种解决方案,推荐使用带有标签的`break`语句来跳出循环,或者使用`goto`语句进行控制流程的跳转,以避免无限循环的发生。
摘要由CSDN通过智能技术生成

问题现象

当for 和 select结合使用时,break语言是无法跳出for之外的:

package main

import (
	"fmt"
	"time"
	"context"
)
func main(){
   
	d := time.Now().Add(3000 * time.Millisecond)
	ctx, cancel := context.WithDeadline(context.Background(), d)

	// Even though ctx will be expired, it is good practice to call its
	// cancelation function in any case. Failure to do so may keep the
	// context and its parent alive longer than necessary.
	defer cancel()

	for{
   
		select {
   
		case 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值