英文:
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 < 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")
}
}
答案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("Name already exists please try another one:\n"))
bytesRead, _ := connection.Read(reply)
name = string(reply[0:bytesRead])
name = strings.TrimSuffix(name, "\n")
continue Loop // Start over
}
}
break // Got through it; we're done
}
You can also just reset your index. range
may be the wrong tool here:
for i := 0; i < len(list.clients); i++ {
client := 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 = -1 // Start again
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论