Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: for loop with range condition to restart

Tags:

go

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

    }
}
like image 426
Timoteo Avatar asked Nov 02 '25 01:11

Timoteo


1 Answers

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
    }
}
like image 194
Rob Napier Avatar answered Nov 04 '25 20:11

Rob Napier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!