问题描述
我想要一组代码被执行,直到用户显式地想要退出该函数。例如:当用户运行该程序时,他将看到2个选项:
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,则与1关联的功能集将执行,如果用户按下2,程序将退出。我应该如何在golang中实现这个场景?在java中,我相信这可以通过do while结构来完成,但不支持while循环。以下是我尝试过的代码,但是这个代码在无限循环中:
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") } } }
不管输入如何,程序只打印hi。有人可以请我改正我在这里做了什么错误吗?
The program irrespective of the input, prints only "hi". Could someone please correct me what wrong i am doing here ?
谢谢。
推荐答案
当这个问题被问及时,这是针对这个特定场景的更好的答案(我很少知道这是在Google搜索do while loop golang时得到的#1结果)。为了回答这个问题,请参阅。
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.
将你的函数封装在for循环中:
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") } }
没有任何声明的循环相当于一个,而其他类似C语言的循环。查看,其中涵盖 code>循环。
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.
这篇关于如何在进行中复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!