for-loopgowhile-loop

How to replicate do while in Go?


I want a set of code to be executed until user explicitly wants to exit the function. For example, when a user runs the program, he will see 2 options:

  1. Run again
  2. Exit

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 Go?

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.


Solution

  • When this question was asked this was a better answer for this specific scenario (little did I know this would be the #1 result when searching Google for "do while loop golang"). For answering this question generically please see @LinearZoetrope's answer below.

    Wrap your function in a for loop:

    package main
    
    import (
        "fmt"
        "os"
    )
    
    func main() {
        fmt.Println("Press 1 to run")
        fmt.Println("Press 2 to exit")
        for {
            sample()
        }
    }
    
    func sample() {
        var input int
        n, err := fmt.Scanln(&input)
        if n < 1 || err != nil {
             fmt.Println("invalid input")
             return
        }
        switch input {
        case 1:
            fmt.Println("hi")
        case 2:
            os.Exit(2)
        default:
            fmt.Println("def")
        }
    }
    

    A for loop without any declarations is equivalent to a while loop in other C-like languages. Check out the Effective Go documentation which covers the for loop.