How to use multiple blank identifiers in go?-ThrowExceptions

Exception or error:

I am trying to use more than one blank identifiers in a loop because I am not interested in the values but I am not able to use it.

Here’s my code

x := [5]float64{1, 2, 3, 4, 5}
for _, _ := range x {
    //Do some work
}   

I am wondering how can one blank identifiers more than once in a statement?

The error I am getting is
no new variables on left side of :=

How to solve:

The code uses short variable declaration, but no new variables are declared because the blank identifier _ does not represent a variable name.

Use the following code:

for _, _ = range x {
    //Do some work
}

Note use of assignment instead of short variable declaration.

Better yet, don’t assign any variables as shown in comment by mh-cbon:

for range {
   //Do some work
}

The variable-free form was added in Go 1.4.

Answer´╝Ü

When none of the variables are being used, you can ignore the blank identifiers.

x := [5]float64{1, 2, 3, 4, 5}
for range x {
    //Do some work
}

As noted by @MonteDude , the _ variable is already defined. This is why you get a no new variables on left side of := error.

Leave a Reply

Your email address will not be published. Required fields are marked *