Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting syntax error: unexpected comma, expecting {

Tags:

go

I was trying for, break and continue in golang and I did this...

func main() {
    for k, i := 0, 0; i < 10; i++, k++ {
        for j := 0; j < 10; j++ {
            if k == 10 {
                fmt.Println("Value of k is:", k)
                break
            }
        }
    }
}

I am getting this syntax error on line of the 1st for:

syntax error: unexpected comma, expecting {

I don't know, how the correct syntax should be instead.

like image 632
NJMR Avatar asked Jun 21 '15 10:06

NJMR


1 Answers

You need to initialize both k and i: for k, i := 0, 0;

Additionally you can't do: i++, k++. Instead you have to do i, k = i+1, k+1

See this reference in Effective Go:

Finally, Go has no comma operator and ++ and -- are statements not expressions. Thus if you want to run multiple variables in a for you should use parallel assignment (although that precludes ++ and --).

// Reverse a

for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 { a[i], a[j] = a[j], a[i] }

func main() {
    for k, i := 0, 0; i < 10;  i, k = i+1, k+1 {
        for j := 0; j < 10; j++ {
            if k == 10 {
                fmt.Println("Value of k is:", k)
                break
            }
        }
    }
}

Note also that k never reaches 10 like this, so your message won't print. You are incrementing i & k at the same time and the outer loop stops at i < 10 (and thus k < 10).

like image 70
IamNaN Avatar answered Oct 07 '22 00:10

IamNaN