Understanding a blank identifier

In “https://play.golang.org/p/6QAnd--O_hP”, does “_” refer to something else in the program?

Does “v” always mean value? or is the “v” here random?

If you mean in for _, v := range ..., ranging over slices will give you two values, the index and a copy of the element at that index. As the program doesn’t use the index, it discards it with _.

The name v is completely arbitrary, you may use whatever identifier you like.

1 Like

Thanks for this.

“As the program doesn’t use the index, it discards it with _ .”

Discards it? Then, what is the purpose of writing it?

Range will give you both values, so you need to deal with them. If instead of _ you declared an actual variable and then just don’t use it, the program won’t compile because there can’t be unused variables. The way of making this work is assigning the value that you don’t care for to the blank identifier. This isn’t limited to range, it works with any multiple assignment, for example functions that return multiple values. You can read more about this here.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.