Underscores in Imports

· 296 words · 2 minutes read

Underscores in Imports

Underscores in Go serve a few purposes. In U+005F, “_” is a letter (as a string). You may also see them as [ “_” ] in between successive digits and a base prefix. In this case, it’s to improve the readability of the code. You may also see them in function names, e.g., imaginary_lit.

The underscore is quite a versatile tool. They even have their place in defining the kind of action that will take place in a function. This is what we know as a blank identifier.

The main ways to use a blank identifier are to discard a value, or values, in a function and create user-defined variables that Go would otherwise not compile. One other use that is not discussed so much is using a blank identifier in import.

Sometimes we will have several packages to import but only need a few of those packages’ init methods (its side-effects), nothing else. When this is the case, you place an underscore in front of the package name.

In the example above, we are importing photos that the program will read in jpeg. The user needs the program to read png and gif as well, but doesn’t need any other feature of the package, just the file type read.

You can similarly use the blank identifier to import databases and other information from packages without having to take on any other aspect of the package to your project. Again, the side effect (what you want/need from that package).

Wrapping Up

As a blank identifier does, it is a simple character with a powerful function associated with it. Not only can it discard values in a one-off inquiry, it can also separate side-effects from the package, making your coding experience easier and cleaner. 

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!