Skip to main content

How to Ignore a Return Value in Go with the Blank Identifier

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Go refuses to compile a program with a local variable it never uses. When a function returns two values and you need only one, put the underscore, _, where the other would go: it accepts the value and throws it away.

Syntax​

Syntax
_, <keep> := <function>()
PartWhat it does
_The blank identifier: takes a value and discards it.
<keep>A normal variable for the value you need.

The Go specification: "The blank identifier is represented by the underscore character _. It serves as an anonymous placeholder instead of a regular (non-blank) identifier".

The Example​

The example has a minMax function that returns the smaller and the larger of two numbers, and keeps only the larger.

Prerequisites​

  • Go. go run compiles and runs a single file. This guide uses Go 1.27.4.

Step 1: Write the Code​

Create a file named main.go:

main.go, which defines minMax(a, b int) returning the smaller and larger number, and assigns _, larger := minMax(8, 3) before printing larger.

main.go
package main

import "fmt"

func minMax(a, b int) (int, int) {
if a < b {
return a, b
}
return b, a
}

func main() {
_, larger := minMax(8, 3)
fmt.Println(larger)
}

Step 2: Run It​

Terminal
go run main.go
Output
8

A zsh terminal where go run main.go prints 8.

The smaller number went into _ and was discarded. The command is the same in zsh, bash and PowerShell.

Why Not Just Name It?​

Name the first value, smaller, larger := minMax(8, 3), without using smaller, and the program doesn't compile: Go reports declared and not used: smaller. The blank identifier says, on purpose, "I don't need this one".

Common Mistakes​

MistakeWhat happensDo this instead
Naming a value you don't usedeclared and not used: smallerReplace it with _
Discarding an error with _Failures go unnoticedKeep the error and check it
Reading from _, as in fmt.Println(_)cannot use _ as value or typeUse a named variable

Troubleshooting​

SymptomLikely causeFix
declared and not usedA variable is assigned but never readUse it, or assign to _
A program silently uses zero valuesAn error was discarded with _Check the error instead

FAQ​

Where else is _ used?​

In for _, item := range items to skip the index, and in import _ "package" to import a package only for its side effects.

Can I use _ several times in one assignment?​

Yes. Each _ discards its own value, as in _, _, c := three().

Conclusion​

Assign values you don't need to _ and Go discards them without complaining about unused variables. Use it for values that really don't matter, never to hide an error.

Additional Resources​