Replication of Do While Loop in Go
In Go, the concept of a while loop does not directly correlate to Java's do while loop. However, there are ways to emulate the functionality of a do while loop using other loop structures available in Go.
Let's delve into the code sample you provided:
var i = 1 for i > 0 { fmt.Println("Press 1 to run") fmt.Println("Press 2 to exit") var input string inpt, _ := fmt.Scanln(&input) switch inpt { case 1: fmt.Println("hi") case 2: os.Exit(2) default: fmt.Println("def") } }
Your code is locked in an infinite loop irrespective of the input because the loop condition i > 0 is always true. To emulate do while behavior, you need to use a different loop structure that checks the loop condition only after the loop body has been executed.
Here's a modified version of your code that achieves the desired functionality:
var input int for { fmt.Println("Press 1 to run") fmt.Println("Press 2 to exit") n, err := fmt.Scanln(&input) if n < 1 || err != nil { fmt.Println("Invalid input") break } switch input { case 1: fmt.Println("hi") case 2: fmt.Println("Exiting...") return default: fmt.Println("Invalid input") } }
In this code:
This code provides the desired behavior of executing the loop body until the user explicitly chooses to exit.
The above is the detailed content of How to Replicate a Do While Loop in Go?. For more information, please follow other related articles on the PHP Chinese website!