How to replicate do while in go?

Issue

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:

  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 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.

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.

Answered By – Lander

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.