Replicating do while Loops in Go
In Go, there is no direct equivalent to the do while loop found in many other programming languages. However, there are ways to achieve similar functionality. One method is to use a for loop with a boolean loop variable initialized to true.
The following code demonstrates how to emulate a do while loop in Go:
for ok := true; ok; ok = EXPR { // Code to be executed }
This loop will continue to execute the code block until the expression EXPR evaluates to false. In the context of the original problem, this expression would be whether the user input matches a desired exit condition.
Here is a modified version of the provided code that correctly implements the desired functionality:
func sample() { for ok := true; ok; ok = (input != 2) { fmt.Println("Press 1 to run") fmt.Println("Press 2 to exit") var input int fmt.Scanln(&input) switch input { case 1: fmt.Println("hi") case 2: // Exit the program os.Exit(2) default: fmt.Println("def") } } }
In this code, the loop continues until the user inputs 2 (to exit). If the input is 1, it executes the "hi" statement. If the input is anything else, it executes the "def" statement.
Note that you can replace os.Exit(2) with an explicit call to return to exit the function early.
The above is the detailed content of How Can You Emulate a Do While Loop in Go?. For more information, please follow other related articles on the PHP Chinese website!