"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Implement a "do while" Loop in Go?

How to Implement a "do while" Loop in Go?

Published on 2024-11-15
Browse:171

How to Implement a

Go Equivalent of Java's "do while" Loop

In Java, a "do while" loop allows a block of code to execute at least once before checking for an exit condition. Go does not have an explicit "do while" loop, but it can be replicated using a for loop with a boolean loop variable set to true.

Corrected Code:

To resolve the infinite loop issue in your code, you need to update the loop condition to check if the user input is equal to 2 (indicating exit). Additionally, you should handle invalid user input.

Here's the corrected code:

func sample() {
    var input int
    for ok := true; ok; ok = (input != 2) {
        fmt.Println("Press 1 to run")
        fmt.Println("Press 2 to exit")
        var inpt, err = fmt.Scanln(&input)
        if inpt 
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3