英文:
How to replicate do while in go?
问题
我想要一段代码,直到用户明确想要退出函数时才执行。例如:当用户运行程序时,他将看到2个选项:
- 再次运行
- 退出
这可以使用switch case结构来实现。如果用户按下1,与1相关联的一组函数将执行,如果用户按下2,程序将退出。我应该如何在Go语言中实现这种情况?在Java中,我相信可以使用do while结构来实现,但Go语言不支持do while循环。以下是我尝试过的代码,但它进入了一个无限循环:
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"。请问有人能纠正我在这里做错了什么吗?
谢谢。
英文:
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:
- Run again
- 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.
答案1
得分: 80
一个 do..while
循环可以在 Go 中通过使用一个以 true
为初始值的 bool
循环变量来更直接地模拟。
for ok := true; ok; ok = EXPR { }
几乎等同于
do { } while(EXPR)
所以在你的情况下:
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:
// 什么都不做(我们想要退出循环)
// 在一个真实的程序中,这可能是清理操作
default:
fmt.Println("def")
}
}
编辑:Playground(使用虚拟的 Stdin)
尽管如此,在这种情况下,直接在循环中明确调用(带标签的)break
、return
或 os.Exit
可能更清晰明了。
英文:
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.
答案2
得分: 14
当这个问题被提出时,这个答案对于这个特定的场景来说是更好的(我并不知道这将成为在谷歌搜索“do while loop golang”时的第一结果)。如果要通用地回答这个问题,请参考@LinearZoetrope的答案。
将你的函数包装在一个for循环中:
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("按1运行")
fmt.Println("按2退出")
for {
sample()
}
}
func sample() {
var input int
n, err := fmt.Scanln(&input)
if n < 1 || err != nil {
fmt.Println("无效的输入")
return
}
switch input {
case 1:
fmt.Println("你好")
case 2:
os.Exit(2)
default:
fmt.Println("默认")
}
}
在其他类似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:
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
得分: 14
在Go语言中,do...while循环可以使用以下方式实现:
func main() {
var value int
for {
value++
fmt.Println(value)
if value%6 != 0 {
break
}
}
}
这段代码会不断地增加value
的值,并打印出来。当value
不能被6整除时,循环会被终止。
英文:
The do...while in go can be this:
func main() {
var value int
for {
value++
fmt.Println(value)
if value%6 != 0 {
break
}
}
}
答案4
得分: 13
在Go语言中,一个while
循环可以这么简单地实现:
package main
import "fmt"
func main() {
for {
var number float64
fmt.Print("请输入一个大于等于10的整数:")
fmt.Scanf("%f", &number)
if number >= 10 {
break
}
fmt.Println("抱歉,数字小于10,请重新输入!")
}
}
这段代码实现了一个无限循环,要求用户输入一个大于等于10的整数,如果输入的数字小于10,则会提示用户重新输入。直到用户输入的数字大于等于10时,循环才会结束。
英文:
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!!!`)
}
答案5
得分: 4
考虑使用"for-break"替代"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
英文:
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
答案6
得分: 2
也许不是你要找的,但如果你想要做类似的事情,你可以这样在Go语言中实现:
package main
import "fmt"
func main() {
i := 0
fmt.Println(i)
for {
if i < 10 {
fmt.Println("incrementing i now")
i++
} else {
break
}
}
fmt.Println("done")
}
这段代码会输出:
0
incrementing i now
incrementing i now
incrementing i now
incrementing i now
incrementing i now
incrementing i now
incrementing i now
incrementing i now
incrementing i now
incrementing i now
done
希望对你有帮助!
英文:
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")
答案7
得分: 1
sum := 1
for sum < 1000 {
sum += sum
}
解释:
基本的for循环由三个部分组成,用分号分隔:
-
init语句:在第一次迭代之前执行。
-
condition表达式:在每次迭代之前进行评估。
-
post语句:在每次迭代结束时执行。
init语句和post语句是可选的。
因此,你可以只放入condition表达式。
// 当(CONDITION = true)时执行以下代码....
// 在Go语言中:
for CONDITION = true {
// 要执行的代码
}
英文:
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}
答案8
得分: 0
这是其中一种最简洁的方式:
num := 10
for num > 0 {
// 在这里执行操作
num--
}
英文:
This is one of the cleanest ways:
num := 10
for num > 0 {
// do stuff here
num--
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论