gpt4 book ai didi

戈朗 : for loop with range condition to restart

转载 作者:IT王子 更新时间:2023-10-29 01:42:42 26 4
gpt4 key购买 nike

每次列表中已经有一个名字时,我都试图让这个循环重新开始,这段代码显然只会检查一次。有没有办法让循环从头开始?谢谢!

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")

}
}

最佳答案

将其包装在另一个 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
}

您也可以只重置索引。 range 可能是这里的错误工具:

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
}
}

关于戈朗 : for loop with range condition to restart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30240439/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com