48

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.

0

8 Answers 8

79

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.

4
  • 1
    This should be accepted answer as it is idiomatic and exactly replicates do while whilst current accepted answer just replicates while statement
    – P.An
    Nov 3, 2017 at 11:41
  • This is a great simple answer, however it doesn't allow you to access variables inside the for scope in the condition. This answer solves this problem. Aug 20, 2019 at 21:40
  • @David Callanan I mean, it's not that hard to fix. Just do ok = ok for the expression and set ok manually at the end of the loop.
    – Linear
    Aug 20, 2019 at 22:54
  • @LinearZoetrope Nice that works too! The condition is full of oks then :) for ok := true; ok; ok = ok { ... } Aug 21, 2019 at 8:48
14

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.

3
  • this only keeps on printing "hi". Even if we give command line input as 2, it prints "hi" instead of exiting the program. Sep 29, 2015 at 2:30
  • My mistake. The switch case needs to be modified.
    – Lander
    Sep 29, 2015 at 2:32
  • 1
    So the mistake with the original input was that the return value from Scanln was being used. The documentation states that the return is an error/number of arguments parsed, which is not how you want to use it. This should get you started.
    – Lander
    Sep 29, 2015 at 2:34
14

The do...while in go can be this:

func main() {
    var value int
    for {
        value++
        fmt.Println(value)
        if value%6 != 0 {
            break
        }
    }
}
1
  • This solution allows you to access variables inside the for scope in the condition, which is necessary in some situations. Aug 20, 2019 at 21:42
13

a while loop in Go can be as easy as this:

  package main

  import `fmt`

      func main() {
        for {
          var number float64
          fmt.Print(`insert an Integer eq or gr than 10!!!`)
          fmt.Scanf(`%f`, &number)
          if number >= 10 { break }
          fmt.Println(`sorry the number is lower than 10....type again!!!`)
        }
4
  • This is an infinite loop declaration, rather than a while loop. A while loop would have a condition. Mar 7, 2017 at 14:09
  • 1
    @VictorZamanian there is a condition: if number >= 10 { break }. For all intents and purposes, an infinite loop with a conditional break at the end is the same as a do..while loop which is exactly what OP was asking for.
    – 3ocene
    Jul 14, 2017 at 22:27
  • @VictorZamanian perhaps I'm missing the point of your comment then. It sounds like you're trying to say that the answer is incorrect or that he's wrong to say that it's emulating a while loop.
    – 3ocene
    Jul 15, 2017 at 2:33
  • 2
    @3ocene No, no. Your reasoning is correct. I probably just missed the condition at the end there when I made my first comment on this answer a while back. My mistake Jul 15, 2017 at 2:38
4

Conside to use "for-break" as "do-while".

foo.go

package main

import (
        "fmt"
)

func main() {
        i := 0
        for {
                i++
                if i > 10 {
                        break
                }
                fmt.Printf("%v ", i)
        }
        fmt.Println()
}

shell

$ go run foo.go
1 2 3 4 5 6 7 8 9 10
1
  • This is the same as for i := 0; i < 10; i++ { fmt.Printf("%v ", i) }. Perhaps you meant to put the print statement at the top of the loop?
    – 3ocene
    Jul 14, 2017 at 22:31
2

Maybe not what you're looking for, but if you're trying to do something like this:

int i = 0;
while (i < 10) {
    cout << "incrementing i now" << endl;
    i++
}
cout << "done"

You'll have to do something like this in go:

    var i = 0 
    fmt.Println(i)
    for {
            if i < 10 {
                    fmt.Println("incrementing i now")
                    i++ 
            } else {
                    break
            }   
    }   
    fmt.Println("done")
1
  • 2
    Go does have regular "while loops" though: for a > b { ... }. What OP is asking for is a do { ... } while (a > b); loop Nov 9, 2016 at 9:09
1
sum := 1
    for sum < 1000 {
        sum += sum
    }

Explanation :

The basic for loop has three components separated by semicolons:

-the init statement: executed before the first iteration.

-the condition expression: evaluated before every iteration

-the post statement: executed at the end of every iteration

The init and post statements are optional.

So you can just put in the condition expression.

// While (CONDITION = true){
//code to execute ....}

//In go : 
for CONDITION = true {
//code to execute}
0

This is one of the cleanest ways:

num := 10
for num > 0 {
    // do stuff here
    num--
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.