3

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!

2
  • Where is i defined in your Javascript code? Commented Jan 6, 2015 at 16:32
  • ive edited the code for clarity Commented Jan 6, 2015 at 16:35

1 Answer 1

8

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.