Struct Tags with Underscore Before Function Names

· 449 words · 3 minutes read

In the Go world, an underscore (_) before an expression is called a blank identifier. As you may already know, identifiers—user-defined program components, e.g., name of a function, variable, or package—in Go must be preceded by an underscore or a letter (a-z or A-Z). If they aren’t, you’ll receive the compile- time error which essentially means Go cannot read the syntax of your code (you didn’t write your code correctly).

Unlike identifiers made of letters, a blank identifier is used as a placeholder for user-defined variables (var) that the user doesn’t store, namely unused variables. Go won’t compile unused variables (unless it’s a global unused variable). The structure of Go doesn’t have the time for your “bad coding.”

Now, you may be used to using unused variables freely in other programming languages, but Go sees them as a bug, which is why we refer to it as “bad coding.” They are forcing you to write concisely. But, if you need/want to keep this unused variable in there, you’ll have to come up with a solution. That solution is to use the underscore, which in the eyes of Go, makes an unused variable “used.”

As such, Go struct tags with an underscore before function names allows you to work around certain aspects of functions, especially if they deal with ranges and multiple values. Though you may not have come across this, especially if you’re more of a beginner and Go is your first language, putting an underscore before a function is a very helpful solution to Go’s insistence that every variable be a used variable.

Examples of Using Go Struct Tags

func sumProduct(a, b int)(int, int) {
    return a+b, a*b

Now, you don’t need the product, just the sum. So you need to create an unused variable that the system will compile (and then forget) without generating an error.

func main() {
	Sum, _ := SumProduct(1,2)

If you do not put in that underscore, you will get an error. In this case, we use the syntax to forget a particular part of a function, [, _:=].

Words of Wisdom

Ultimately, the key thing to remember is this: if you don’t want all of a function or want to bypass variable data, you can’t just do it with the usual loose coding you may be familiar with from other programs. You need to use the blank identifier. However, don’t use blank identifiers randomly. Though they aren’t stored, they still require memory. The idea behind Go is to have a sleek, clean, and concise way to write code. Don’t junk it up with blank identifiers. Try to find the Go way to do it.

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!