Golang:使用范围条件的for循环重新启动

huangapple go评论83阅读模式
英文:

Golang: for loop with range condition to restart

问题

我正在尝试使这个循环在列表中已经存在一个名称时重新开始,这段代码显然只会检查一次。有没有办法让循环从头开始重新执行?谢谢!

for _, client := range list.clients {
	//for i := 0; i < len(list.clients); i++ {
		if(client.name==name){
			connection.Write([]byte("Name already exists please try another one:\n"))
			bytesRead, _ := connection.Read(reply)
       			name = string(reply[0:bytesRead])
			name = strings.TrimSuffix(name, "\n")
				
		}
	}
英文:

I'm trying to make this loop restart every time a name is already in the list, this code is obviously only going to check this once. Is there any way to make the loop restart from beginning? Thanks!

for _, client := range list.clients {
//for i := 0; i &lt; len(list.clients); i++ {
	if(client.name==name){
		connection.Write([]byte(&quot;Name already exists please try another one:\n&quot;))
		bytesRead, _ := connection.Read(reply)
   			name = string(reply[0:bytesRead])
		name = strings.TrimSuffix(name, &quot;\n&quot;)
			
	}
}

答案1

得分: 5

将其包装在另一个for循环中:

Loop:
	for {
		for _, client := range list.clients {
			if client.name == name {
				connection.Write([]byte("名称已存在,请尝试另一个名称:\n"))
				bytesRead, _ := connection.Read(reply)
				name = string(reply[0:bytesRead])
				name = strings.TrimSuffix(name, "\n")
				continue Loop // 重新开始
			}
		}
		break // 完成了; 我们结束了
	}

你也可以重置索引。range可能不是合适的工具:

for i := 0; i < len(list.clients); i++ {
	client := list.clients[i]
	if client.name == name {
		connection.Write([]byte("名称已存在,请尝试另一个名称:\n"))
		bytesRead, _ := connection.Read(reply)
		name = string(reply[0:bytesRead])
		name = strings.TrimSuffix(name, "\n")
		i = -1 // 重新开始
	}
}
英文:

Wrap it in another for:

Loop:
	for {
		for _, client := range list.clients {
			if client.name == name {
				connection.Write([]byte(&quot;Name already exists please try another one:\n&quot;))
				bytesRead, _ := connection.Read(reply)
				name = string(reply[0:bytesRead])
				name = strings.TrimSuffix(name, &quot;\n&quot;)
				continue Loop // Start over
			}
		}
		break // Got through it; we&#39;re done
	}

You can also just reset your index. range may be the wrong tool here:

for i := 0; i &lt; len(list.clients); i++ {
	client := list.clients[i]
	if client.name == name {
		connection.Write([]byte(&quot;Name already exists please try another one:\n&quot;))
		bytesRead, _ := connection.Read(reply)
		name = string(reply[0:bytesRead])
		name = strings.TrimSuffix(name, &quot;\n&quot;)
		i = -1 // Start again
	}
}

huangapple
  • 本文由 发表于 2015年5月14日 22:51:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/30240439.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定