Vrushank Doshi
Vrushank Doshi

Reputation: 2608

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.

Upvotes: 57

Views: 86208

Answers (8)

Emmanuel
Emmanuel

Reputation: 5395

This is one of the cleanest ways:

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

Upvotes: 2

Rabhi salim
Rabhi salim

Reputation: 506

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}

Upvotes: 1

Lander
Lander

Reputation: 3437

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.

Upvotes: 16

lolita
lolita

Reputation: 191

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

func main() {
    var value int
    for {
        value++
        fmt.Println(value)
        if value%6 != 0 {
            break
        }
    }
}

Upvotes: 19

Jon X
Jon X

Reputation: 9133

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

Upvotes: 4

user3165213
user3165213

Reputation: 141

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!!!`)
        }

Upvotes: 14

Alexander Kleinhans
Alexander Kleinhans

Reputation: 6248

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")

Upvotes: 2

Linear
Linear

Reputation: 22196

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.

Upvotes: 94

Related Questions