What is "_," (underscore comma) in a Go declaration?

VariablesGo

Variables Problem Overview


And I can't seem to understand this kind of variable declaration:

_, prs := m["example"]

What exactly is "_," doing and why have they declared a variable like this instead of

prs := m["example"]

(I found it as part of Go by Example: Maps)

Variables Solutions


Solution 1 - Variables

It avoids having to declare all the variables for the returns values.
It is called the blank identifier.

As in:

_, y, _ := coord(p)  // coord() returns three values; only interested in y coordinate

That way, you don't have to declare a variable you won't use: Go would not allow it. Instead, use '_' to ignore said variable.

(the other '_' use case is for import)

Since it discards the return value, it is helpful when you want to check only one of the returned values, as in "How to test key existence in a map?" shown in "Effective Go, map":

_, present := timeZone[tz]

> To test for presence in the map without worrying about the actual value, you can use the blank identifier, a simple underscore (_).
The blank identifier can be assigned or declared with any value of any type, with the value discarded harmlessly.
For testing presence in a map, use the blank identifier in place of the usual variable for the value.

As Jsor adds in the comments:

> "generally accepted standard" is to call the membership test variables "ok" (same for checking if a channel read was valid or not)

That allows you to combine it with test:

if _, err := os.Stat(path); os.IsNotExist(err) {
	fmt.Printf("%s does not exist\n", path)
}

You would find it also in loop:

> If you only need the second item in the range (the value), use the blank identifier, an underscore, to discard the first:

sum := 0
for _, value := range array {
    sum += value
}

Solution 2 - Variables

The Go compiler won't allow you to create variables that you never use.

for i, value := range x {
   total += value
}

The above code will return an error message "i declared and not used".

Since we don't use i inside of our loop we need to change it to this:

for _, value := range x {
   total += value
}

Solution 3 - Variables

>The blank identifier may be used whenever syntax requires a variable name but program logic does not, for instance to discard an unwanted loop index when we require only the element value.

Excerpt From:

The Go Programming Language (Addison-Wesley Professional Computing Series)

Brian W. Kernighan

This material may be protected by copyright.

Solution 4 - Variables

_ is the blank identifier. Meaning the value it should be assigned is discarded.

Here it is the value of example key that is discarded. The second line of code would discard the presence boolean and store the value in prs.
So to only check the presence in the map, you can discard the value. This can be used to use a map as a set.

Solution 5 - Variables

The great use case for the unused variable is the situation when you only need a partial output. In the example below we only need to print the value (state population).

package main
import (
	"fmt"
)
func main() {
          statePopulations := map[string]int{
		  "California": 39250017,
		  "Texas":      27862596,
		  "Florida":    20612439,
	      }
	      for _, v := range statePopulations {
		  fmt.Println(v)
	}
}

Solution 6 - Variables

It is called the blank identifier and it helps in cases where you wish to discard the value that is going to be returned and not reference it

Some places where we use it:

  • A function returns a value and you don't intend to use it in the future
  • You want to iterate and need an i value that you will not be using

Solution 7 - Variables

Basically, _, known as the blank identifier. In GO we can't have variables that are not being used.

As an instance when you iterating through an array if you are using value := range you don't want a i value for iterating. But if you omit the i value it will return an error. But if you declare i and didn't use it, it will also return an error.

Therefore, that is the place where we have to use _,.

Also it is used when you don't want a function's return value in the future.

Solution 8 - Variables

> An unused variable is not allowed in Golang

If you were coming from other programming languages this might feel bit difficult to get used to this. But this results in more cleaner code. So by using a _ we are saying we know there is a variable there but we don't want to use it and telling the compiler that does not complain me about it. :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKansulerView Question on Stackoverflow
Solution 1 - VariablesVonCView Answer on Stackoverflow
Solution 2 - VariablesJuni BrosasView Answer on Stackoverflow
Solution 3 - VariableskoopertrooperView Answer on Stackoverflow
Solution 4 - VariablesThinkChaosView Answer on Stackoverflow
Solution 5 - VariablesmonkrusView Answer on Stackoverflow
Solution 6 - VariablesAnaghaView Answer on Stackoverflow
Solution 7 - VariablesKaveen HyacinthView Answer on Stackoverflow
Solution 8 - VariablesKrishnadas PCView Answer on Stackoverflow