Understanding a blank identifier


(Cherolyn Lexvold) #1

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


(Cherolyn Lexvold) #2

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


(Ignacio Gómez) #3

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.


(Cherolyn Lexvold) #4

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?


(Ignacio Gómez) #5

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.