Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/32834661/how-to-replicate-do-while-in-go

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...