I want a set of code to be executed until user explicitly wants to exit the function. For eg: when a user runs the program, he will see 2 options:
this will be achieved using switch case structure. Here if user presses 1, set of functions associated with 1 will execute and if user presses 2, the program will exit. How should i achieve this scenario in golang ? In java, i believe this could be done using do while structure but go doesn't support do while loop. Following is my code which i tried but this goes in a infinite loop:
func sample() { 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") } } }
The program irrespective of the input, prints only "hi". Could someone please correct me what wrong i am doing here ?
Thanks.
In Go, there is no special expression to create the do-while loop, but we can easily simulate it using a for loop. We just need to ensure that it executes at least once.
A do..while
can more directly be emulated in Go with a for loop using a bool
loop variable seeded with true
.
for ok := true; ok; ok = EXPR { }
is more or less directly equivalent to
do { } while(EXPR)
So in your case:
var input int for ok := true; ok; ok = (input != 2) { n, err := fmt.Scanln(&input) if n < 1 || err != nil { fmt.Println("invalid input") break } switch input { case 1: fmt.Println("hi") case 2: // Do nothing (we want to exit the loop) // In a real program this could be cleanup default: fmt.Println("def") } }
Edit: Playground (with a dummied-out Stdin)
Though, admittedly, in this case it's probably overall clearer to just explicitly call (labelled) break
, return
, or os.Exit
in the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With