Go core · 3 MIN READ

An unused variable stops the build

Recognise the two unused errors on sight and know why they exist.

Go refuses to compile a function with a variable it never reads, and a file with an import it never uses. Not a warning — an error.

This feels hostile for about a week. What it buys is that dead code cannot accumulate quietly, and that a half-finished edit fails loudly instead of shipping. The escape hatch when you genuinely need it is assignment to _, which says "deliberately discarded" out loud.

SEE THE IDEA

Every local name needs a purpose

  1. 01

    Import

    go
    import "fmt"

    A file must use its imports

  2. 02

    Local variable

    go
    label := "go"

    A declared local must be used

  3. 03

    Intentional discard

    go
    _, err := read()

    The blank identifier names no variable

Go checks unused imports per file and unused local variables at compile time.

In practice

During a repair, decide whether the unused value belongs in the result or should be removed. Keep imports close to the code that needs them. The blank identifier is useful for an intentionally ignored result, but removing dead work usually makes the program clearer.

Watch out

A blank assignment only satisfies the compiler. It does not explain why calculating an unused value was necessary.

Official reference ↗

Work through the exercise

go
package main

import (
	"fmt"
	"os"
)

func main() {
	host := "localhost"
	port := 8080
	fmt.Println(port)
}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.