如何在Go语言中复制do-while循环?

huangapple go评论124阅读模式
英文:

How to replicate do while in go?

问题

我想要一段代码,直到用户明确想要退出函数时才执行。例如:当用户运行程序时,他将看到2个选项:

  1. 再次运行
  2. 退出

这可以使用switch case结构来实现。如果用户按下1,与1相关联的一组函数将执行,如果用户按下2,程序将退出。我应该如何在Go语言中实现这种情况?在Java中,我相信可以使用do while结构来实现,但Go语言不支持do while循环。以下是我尝试过的代码,但它进入了一个无限循环:

  1. func sample() {
  2. var i = 1
  3. for i > 0 {
  4. fmt.Println("Press 1 to run")
  5. fmt.Println("Press 2 to exit")
  6. var input string
  7. inpt, _ := fmt.Scanln(&input)
  8. switch inpt {
  9. case 1:
  10. fmt.Println("hi")
  11. case 2:
  12. os.Exit(2)
  13. default:
  14. fmt.Println("def")
  15. }
  16. }
  17. }

无论输入是什么,程序都只打印"hi"。请问有人能纠正我在这里做错了什么吗?

谢谢。

英文:

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:

  1. func sample() {
  2. var i = 1
  3. for i > 0 {
  4. fmt.Println("Press 1 to run")
  5. fmt.Println("Press 2 to exit")
  6. var input string
  7. inpt, _ := fmt.Scanln(&input)
  8. switch inpt {
  9. case 1:
  10. fmt.Println("hi")
  11. case 2:
  12. os.Exit(2)
  13. default:
  14. fmt.Println("def")
  15. }
  16. }
  17. }

The program irrespective of the input, prints only "hi". Could someone please correct me what wrong i am doing here ?

Thanks.

答案1

得分: 80

一个 do..while 循环可以在 Go 中通过使用一个以 true 为初始值的 bool 循环变量来更直接地模拟。

  1. for ok := true; ok; ok = EXPR { }

几乎等同于

  1. do { } while(EXPR)

所以在你的情况下:

  1. var input int
  2. for ok := true; ok; ok = (input != 2) {
  3. n, err := fmt.Scanln(&input)
  4. if n < 1 || err != nil {
  5. fmt.Println("invalid input")
  6. break
  7. }
  8. switch input {
  9. case 1:
  10. fmt.Println("hi")
  11. case 2:
  12. // 什么都不做(我们想要退出循环)
  13. // 在一个真实的程序中,这可能是清理操作
  14. default:
  15. fmt.Println("def")
  16. }
  17. }

编辑:Playground(使用虚拟的 Stdin)

尽管如此,在这种情况下,直接在循环中明确调用(带标签的)breakreturnos.Exit 可能更清晰明了。

英文:

A do..while can more directly be emulated in Go with a for loop using a bool loop variable seeded with true.

  1. for ok := true; ok; ok = EXPR { }

is more or less directly equivalent to

  1. do { } while(EXPR)

So in your case:

  1. var input int
  2. for ok := true; ok; ok = (input != 2) {
  3. n, err := fmt.Scanln(&input)
  4. if n < 1 || err != nil {
  5. fmt.Println("invalid input")
  6. break
  7. }
  8. switch input {
  9. case 1:
  10. fmt.Println("hi")
  11. case 2:
  12. // Do nothing (we want to exit the loop)
  13. // In a real program this could be cleanup
  14. default:
  15. fmt.Println("def")
  16. }
  17. }

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.

答案2

得分: 14

当这个问题被提出时,这个答案对于这个特定的场景来说是更好的(我并不知道这将成为在谷歌搜索“do while loop golang”时的第一结果)。如果要通用地回答这个问题,请参考@LinearZoetrope的答案

将你的函数包装在一个for循环中:

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func main() {
  7. fmt.Println("按1运行")
  8. fmt.Println("按2退出")
  9. for {
  10. sample()
  11. }
  12. }
  13. func sample() {
  14. var input int
  15. n, err := fmt.Scanln(&input)
  16. if n < 1 || err != nil {
  17. fmt.Println("无效的输入")
  18. return
  19. }
  20. switch input {
  21. case 1:
  22. fmt.Println("你好")
  23. case 2:
  24. os.Exit(2)
  25. default:
  26. fmt.Println("默认")
  27. }
  28. }

在其他类似C语言的语言中,没有任何声明的for循环等同于while循环。请查看Effective Go文档中关于for循环的内容。

英文:

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:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;os&quot;
  5. )
  6. func main() {
  7. fmt.Println(&quot;Press 1 to run&quot;)
  8. fmt.Println(&quot;Press 2 to exit&quot;)
  9. for {
  10. sample()
  11. }
  12. }
  13. func sample() {
  14. var input int
  15. n, err := fmt.Scanln(&amp;input)
  16. if n &lt; 1 || err != nil {
  17. fmt.Println(&quot;invalid input&quot;)
  18. return
  19. }
  20. switch input {
  21. case 1:
  22. fmt.Println(&quot;hi&quot;)
  23. case 2:
  24. os.Exit(2)
  25. default:
  26. fmt.Println(&quot;def&quot;)
  27. }
  28. }

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

得分: 14

在Go语言中,do...while循环可以使用以下方式实现:

  1. func main() {
  2. var value int
  3. for {
  4. value++
  5. fmt.Println(value)
  6. if value%6 != 0 {
  7. break
  8. }
  9. }
  10. }

这段代码会不断地增加value的值,并打印出来。当value不能被6整除时,循环会被终止。

英文:

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

  1. func main() {
  2. var value int
  3. for {
  4. value++
  5. fmt.Println(value)
  6. if value%6 != 0 {
  7. break
  8. }
  9. }
  10. }

答案4

得分: 13

在Go语言中,一个while循环可以这么简单地实现:

  1. package main
  2. import "fmt"
  3. func main() {
  4. for {
  5. var number float64
  6. fmt.Print("请输入一个大于等于10的整数:")
  7. fmt.Scanf("%f", &number)
  8. if number >= 10 {
  9. break
  10. }
  11. fmt.Println("抱歉,数字小于10,请重新输入!")
  12. }
  13. }

这段代码实现了一个无限循环,要求用户输入一个大于等于10的整数,如果输入的数字小于10,则会提示用户重新输入。直到用户输入的数字大于等于10时,循环才会结束。

英文:

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

  1. package main
  2. import `fmt`
  3. func main() {
  4. for {
  5. var number float64
  6. fmt.Print(`insert an Integer eq or gr than 10!!!`)
  7. fmt.Scanf(`%f`, &amp;number)
  8. if number &gt;= 10 { break }
  9. fmt.Println(`sorry the number is lower than 10....type again!!!`)
  10. }

答案5

得分: 4

考虑使用"for-break"替代"do-while"。

foo.go

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. i := 0
  7. for {
  8. i++
  9. if i > 10 {
  10. break
  11. }
  12. fmt.Printf("%v ", i)
  13. }
  14. fmt.Println()
  15. }

shell

  1. $ go run foo.go
  2. 1 2 3 4 5 6 7 8 9 10
英文:

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

foo.go

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. )
  5. func main() {
  6. i := 0
  7. for {
  8. i++
  9. if i &gt; 10 {
  10. break
  11. }
  12. fmt.Printf(&quot;%v &quot;, i)
  13. }
  14. fmt.Println()
  15. }

shell

  1. $ go run foo.go
  2. 1 2 3 4 5 6 7 8 9 10

答案6

得分: 2

也许不是你要找的,但如果你想要做类似的事情,你可以这样在Go语言中实现:

  1. package main
  2. import "fmt"
  3. func main() {
  4. i := 0
  5. fmt.Println(i)
  6. for {
  7. if i < 10 {
  8. fmt.Println("incrementing i now")
  9. i++
  10. } else {
  11. break
  12. }
  13. }
  14. fmt.Println("done")
  15. }

这段代码会输出:

  1. 0
  2. incrementing i now
  3. incrementing i now
  4. incrementing i now
  5. incrementing i now
  6. incrementing i now
  7. incrementing i now
  8. incrementing i now
  9. incrementing i now
  10. incrementing i now
  11. incrementing i now
  12. done

希望对你有帮助!

英文:

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

  1. int i = 0;
  2. while (i &lt; 10) {
  3. cout &lt;&lt; &quot;incrementing i now&quot; &lt;&lt; endl;
  4. i++
  5. }
  6. cout &lt;&lt; &quot;done&quot;

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

  1. var i = 0
  2. fmt.Println(i)
  3. for {
  4. if i &lt; 10 {
  5. fmt.Println(&quot;incrementing i now&quot;)
  6. i++
  7. } else {
  8. break
  9. }
  10. }
  11. fmt.Println(&quot;done&quot;)

答案7

得分: 1

sum := 1
for sum < 1000 {
sum += sum
}

解释:

基本的for循环由三个部分组成,用分号分隔:

  • init语句:在第一次迭代之前执行。

  • condition表达式:在每次迭代之前进行评估。

  • post语句:在每次迭代结束时执行。

init语句和post语句是可选的。

因此,你可以只放入condition表达式。

// 当(CONDITION = true)时执行以下代码....
// 在Go语言中:
for CONDITION = true {
// 要执行的代码
}

英文:
  1. sum := 1
  2. for sum &lt; 1000 {
  3. sum += sum
  4. }

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.

  1. // While (CONDITION = true){
  2. //code to execute ....}
  3. //In go :
  4. for CONDITION = true {
  5. //code to execute}

答案8

得分: 0

这是其中一种最简洁的方式:

  1. num := 10
  2. for num > 0 {
  3. // 在这里执行操作
  4. num--
  5. }
英文:

This is one of the cleanest ways:

  1. num := 10
  2. for num &gt; 0 {
  3. // do stuff here
  4. num--
  5. }

huangapple
  • 本文由 发表于 2015年9月29日 10:20:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/32834661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定