带有简短语句的 while 循环

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

While loop with a short statement

问题

我对Go语言还不太熟悉,但是我已经遇到了几个情况,我想使用类似于while循环的东西,并且带有一个简短的语句(请参见下面的示例)。是否有可能实现这样的功能?我相信一定有一种简单的方法来实现这个,但是我在互联网上找不到相关的信息。

示例:
(注意:我知道这些示例中的语法在Go中不被支持,我只是使用与if with a short statement相同的语法来说明我的问题)

// 从队列中弹出元素,直到返回nil
for val := queue.Pop(); val != nil {

}
// 扫描数字直到EOF(在竞技编程中,检查err是否为nil足够了)
var n int
for _, err := fmt.Scan(&n); err != nil {

}
英文:

I am quite new to Go and I already had a few occasions where I would like to use something like a while loop with a short statement (see examples below). Is something like that possible? I am pretty sure there must be some simple way to accomplish this but I was unable to find anything on the internet.

Examples:
(NOTE: I am aware the syntax in these examples isn't supported by Go, I just used the same syntax as in if with a short statement to illustrate my issue)

// pop from queue until it returns nil
for val := queue.Pop(); val != nil {

}
// scan numbers until EOF (enough to check if err is nil for competitive programming)
var n int
for _, err := fmt.Scan(&n); err != nil {

}

答案1

得分: 4

你想要的功能没有直接的语法,但有一些选项可以相对简洁地表达你的意图。

要么将声明放在for循环内部:

for {
    val := queue.Pop()
    if val == nil { break }
    ...
}

要么重复表达式:

for val := queue.Pop(); val != nil; val = queue.Pop() {
    ...
}

或者以不同的方式表达循环条件(我猜测这里的queue是什么,使用len可能不是正确的方法,具体取决于你的队列类型)。

for len(queue) > 0 {
   val := queue.Pop()
   ...
}
英文:

There's not syntax for doing exactly what you want, but there's some options for expressing your intention relatively concisely.

Either you move the declaration inside the for loop:

for {
    val := queue.Pop()
    if val == nil { break }
    ...
}

Or you duplicate the expression:

for val := queue.Pop(); val != nil; val = queue.Pop() {
    ...
}

Or you express the loop condition differently (I'm guessing what queue is here, using len may not be the right way to find out if the queue is empty or not depending exactly what your queue type is).

for len(queue) > 0 {
   val := queue.Pop()
   ...
}

huangapple
  • 本文由 发表于 2021年12月11日 21:49:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/70315715.html
匿名

发表评论

匿名网友

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

确定