Multiple variables in for loop in Go

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

Multiple variables in for loop in Go

问题

我正在尝试在Go语言中使用多个变量编写for循环。

来自JavaScript世界,我想实现类似这样的效果:

    var i = 10;
    var b = 2;
    for (var a = b; i; i /= 2, b *= b ) {
      // 一些代码
    }

我尝试了一个类似的“原始翻译”:

   i, b := 10, 2
   for a := b; i; i /= 2, b *= b {
      // 一些代码
    }

但它不起作用。正确的语法是什么?

非常感谢!

英文:

I am trying to write a for loop in Go with multiple variables.

Coming from the javascript world, I'd like to achieve something like this:

    var i = 10;
    var b = 2;
    for (var a = b; i; i /= 2, b *= b ) {
      // some code
    }

I've tried a 'raw translation' like this:

   i, b := 10, 2
   for a := b; i; i /= 2, b *= b {
      // some code
    }

But it doesn't work. What is the proper syntax?

Many thanks!

答案1

得分: 8

在Go语言中,你可以像这样在循环中进行多个变量赋值。

package main

func main() {
    var (
        i = 10
        b = 2
    )
    for a := b; i != 0; i, b = i/2, b*b {
      // 一些代码
    }
}
英文:

In Go, you can do multiple variable assignment in a loop like so.

package main

func main() {
	var (
		i = 10
		b = 2
	)
	for a := b; i != 0; i, b = i/2, b*b {
	  // some code
	}
}

huangapple
  • 本文由 发表于 2015年1月7日 00:26:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/27802873.html
匿名

发表评论

匿名网友

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

确定