4

I'm new to Go and came across this line of code while browsing through some other threads:

if _, err := os.Stat("/path/to/whatever"); os.IsNotExist(err)

What does the _, after the if mean? Is it specifying that something will be assigned in the if condition (as it appears is happening with err)? I couldn't find an example of this syntax on the wiki and I'm very curious to see what it's used for.

Here's a link to the thread I was looking at if it helps: How to check if a file exists in Go?

Flimzy
  • 60,850
  • 13
  • 104
  • 147
  • 3
    https://golang.org/ref/spec#Blank_identifier — please try to do a little bit more research before asking a question. – 9000 Dec 03 '15 at 20:00
  • @9000 Yes, and [ridiculous](https://stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array) [questions](https://stackoverflow.com/questions/927358/how-to-undo-the-last-commits-in-git) [like](https://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type) [these](https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do) get upvoted. The whole point of StackOverflow is to ask. – mid Dec 03 '17 at 16:11
  • 2
    @9000 Also, if you didn't know it was called a blank identifier, I imagine it would be fairly difficult to find the answer – Zac Sep 23 '18 at 11:20

1 Answers1

8

Because os.Stat returns two values, you have to have somewhere to receive those if you want any of them. The _ is a placeholder that essentially means "I don't care about this particular return value." Here, we only care to check the error, but don't need to do anything with the actual FileInfo Stat gives us.

The compiler will just throw that value away.

captncraig
  • 19,430
  • 11
  • 95
  • 139