Go

Fix Go "Undefined: ..." Compile Errors — Identifiers, Scope, and Package Qualifiers

The compiler looked for the name at the exact point where the code uses it, in the scopes that surround that point, and found no declaration. That is all undefined: name ever means — but the reason there is no declaration in scope differs from case to case: the name was never declared, it was spelled differently when it was declared, its declaration comes later in the same function, its block has already closed, or it belongs to a package and the qualifier or the import that makes it reachable is missing. Each section below takes one shape, shows the exact message it prints, and gives the fix that belongs to that shape.

Written November 19, 2026 · Tested with Go 1.26.4 · 15 min read

By the end of this guide
  • The first error: a name that was never declared
  • Reading the message: position first, then the name
  • Typo and case: the declaration exists, the spelling does not match
  • Use before declaration: local scope begins at the end of the declaration

What this guide is

undefined: total is the compiler reporting a failed lookup. Before it can check a value's type, or whether a call has the right number of arguments, it has to find what the name in the code refers to — and at that point in the program, in the scopes open at that point, there is no declaration with that spelling. The message is short because the failure is early: nothing else about the statement is judged until the name resolves.

That single message covers several different defects, and they do not share a fix. Declaring the name fixes a name that was never declared and breaks nothing. Declaring it does nothing for a typo, because the program then holds two variables where it meant to hold one. Moving a declaration fixes a use that stands before it and does nothing for a use that stands after its block has closed. Adding an import fixes a package name and does nothing for a function name used without its qualifier. The sections below separate the shapes by the position and the name in the message, which together identify the shape in almost every case. The examples here use Go 1.26.4. Every example lives in a single file named main.go inside one module, created once from an empty directory:

Terminal
$ mkdir undefined
$ cd undefined
$ go mod init example.com/undefined
go: creating new go.mod: module example.com/undefined

Each program that follows replaces the contents of that main.go. When a build fails, the compiler prints the module path as a header line above the error — # example.com/undefined here.

The first error: a name that was never declared

The smallest program that earns the message uses a name that appears nowhere else in the file:

Go
// main.go
package main

import "fmt"

func main() {
    fmt.Println(total)
}
Terminal
$ go build
# example.com/undefined
./main.go:6:14: undefined: total

Reading the message: position first, then the name

The position, ./main.go:6:14, points at the use, not at any declaration: line 6 is the fmt.Println(total) statement, and column 14 is where total begins in it. The compiler does not point at the place where a declaration should go, because it does not know where that is — or whether a declaration is even the right repair. It knows only that this use, here, resolves to nothing.

The name after the colon is the exact spelling that failed to resolve. That precision is what makes the message diagnostic. Read it literally and compare it, character by character, with the spelling at the declaration you expected it to find. In the program above there is no declaration to compare with, and that is the first shape: the value was computed somewhere, or meant to be, and the statement that was supposed to create the variable is missing, was deleted, or declares the result under a different name that the rest of the function never uses. The fix is a declaration before the use — total := 0 followed by the statements that build the value up, or the single statement that computes it — placed in a scope that still covers the use, a qualification the scope sections below make precise.

Note what the error is not. It is not a complaint that total has the wrong type, holds the wrong value, or is never assigned. Those questions come after resolution, and a name that does not resolve never reaches them. It is also not the unused-variable error: that error is about a declaration nothing uses, and this one is about a use nothing declares. The two are companions — adding a declaration in the wrong scope can trade one for the other — and the related guides at the end cover the unused side.

Typo and case: the declaration exists, the spelling does not match

The most common shape in working code is a declaration that stands a few lines above the failing use, spelled almost — but not exactly — the same:

Go
// main.go
package main

import "fmt"

func main() {
    totalCount := 3
    fmt.Println(totalcount)
    _ = totalCount
}
Terminal
$ go build
# example.com/undefined
./main.go:7:14: undefined: totalcount

The message names totalcount, with a lowercase c. The declared name is totalCount, with an uppercase one. Go identifiers are case-sensitive: those are two different spellings, so far as the compiler is concerned two different names, and only one of them was declared. The _ = totalCount line changes nothing about this error; it keeps the unused-variable error out of the way so this message stands alone.

The fix is to make the two spellings agree — almost always by correcting the use to match the declaration, since the declaration is the spelling the rest of the code was written against. Do not fix this shape by declaring the second spelling. totalcount := 0 above the print would silence the message and create the quieter defect: two counters, one holding the accumulated value and one being printed.

Case matters in a second place as well, and the compiler's wording there is more helpful. The first letter of an identifier decides whether it is exported — visible outside its package — or unexported. A qualified name that reaches for an unexported member of another package fails with a hint attached:

Go
// main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(math.pi)
}
Terminal
$ go build
# example.com/undefined
./main.go:9:19: undefined: math.pi (but have Pi)

The constant in package math is Pi, with an uppercase P, and only the exported spelling can be named from another package. The compiler reports the qualified name as written, math.pi, and adds (but have Pi) — the exported name it does have. That parenthetical is part of this shape only: a plain local typo, as in the totalcount program above, earns no suggestion, because the compiler offers no guess about which local name was meant. Where the hint appears, take it literally; where it does not, the character-by-character comparison against the declaration is the whole method.

Use before declaration: local scope begins at the end of the declaration

A declaration later in the same function does not rescue a use that stands before it:

Go
// main.go
package main

import "fmt"

func main() {
    fmt.Println(x)
    x := 1
    _ = x
}
Terminal
$ go build
# example.com/undefined
./main.go:6:14: undefined: x

The declaration exists. It is one line too late. The specification states the rule directly: the scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec — for a short variable declaration, at the end of the ShortVarDecl — and ends at the end of the innermost containing block. Before that point the name is not in scope, however close the declaration stands, and a use there is undefined in exactly the same words as a use of a name that is never declared at all.

One consequence of "begins at the end" is worth seeing on its own, because it decides what a declaration's own right side may refer to. In a first declaration, the name being declared is not yet in scope on the right side of its own :=:

Go
// main.go
package main

import "fmt"

func main() {
    x := x + 1
    fmt.Println(x)
}
Terminal
$ go build
# example.com/undefined
./main.go:6:7: undefined: x

The position, column 7, is the x on the right side. There is no outer x in this program for that use to fall back to, so it resolves to nothing. The fix for both programs in this section is ordering: move the declaration above every use that needs it, and compute an initial value from names that are already in scope — other variables, parameters, or package-level names — never from the variable being declared.

The contrast: package-level names are in scope for the whole package

The ordering rule above is a rule about local scope, and it does not extend to package level. The scope of an identifier declared in the package block is the entire package block, so a function may call another function whose declaration stands later in the same file — or in another file of the same package:

Go
// main.go
package main

import "fmt"

func main() {
    fmt.Println(helper())
}

func helper() int {
    return 42
}
Terminal
$ go run main.go
42

The program prints 42. main calls helper on a line above helper's declaration, and no error arises, because at package level there is no "before the declaration" in the local sense: every package-level declaration is in scope everywhere in the package, and the order of declarations within and across the package's files does not decide what may refer to what.

Hold the two rules side by side, because confusing them is what makes this error feel inconsistent when it first appears. Inside a function, a local name is usable only from the end of its declaration to the end of its block. At package level, a name is usable throughout the package regardless of where its declaration stands. A reader who moves a helper function below main and a local variable below its first use in the same edit has made one harmless change and one breaking change, and only the second prints this guide's message.

Scope ending: a name used after its block

Scope ends as firmly as it begins. A variable declared inside a block — a braced block, or the body of an if or for statement — belongs to that block, and a use after the block closes finds no declaration:

Go
// main.go
package main

import "fmt"

func main() {
    if true {
        msg := "hi"
        fmt.Println(msg)
    }
    fmt.Println(msg)
}
Terminal
$ go build
# example.com/undefined
./main.go:10:14: undefined: msg

The failing use is the second print, on line 10, outside the braces. The first print, inside the block, is legal and is not the problem. Nothing about the declaration was wrong; it simply ended, as the specification puts it, at the end of the innermost containing block. The fix depends on the intent. If the value is needed after the block, declare the variable before the block and assign inside it — msg := "" before the if, msg = "hi" inside it — so the variable's block is the function body and it outlives the statement. If the value is needed only inside, move the use inside with it.

The loop variable is the same shape in the form working code meets most often. A variable declared by a for initializer is scoped to the for statement:

Go
// main.go
package main

import "fmt"

func main() {
    for i := 0; i < 1; i++ {
    }
    fmt.Println(i)
}
Terminal
$ go build
# example.com/undefined
./main.go:8:14: undefined: i

The message is undefined: i, at the use after the loop. A result that must outlive a loop — the last index, a flag set on the final iteration, a value found by searching — has to live in a variable declared before the loop, with the loop's statements assigning to it. The loop variable itself is gone when the statement ends, by design: it was declared for the statement, not for the function.

Missing package qualifier: the function exists, in another package

A name that belongs to a package cannot be used bare. Println is a function in package fmt; written without the qualifier, it is looked up among the current package's own names and the local scopes, and it is in none of them:

Go
// main.go
package main

func main() {
    Println("hi")
}
Terminal
$ go build
# example.com/undefined
./main.go:4:2: undefined: Println

The message names Println alone, because that is the identifier the code offered. The fix is the qualified identifier: a package name prefix, a dot, and the identifier — fmt.Println — together with the import that makes the package available. A qualified identifier accesses an identifier in a different package, which must be imported, and the identifier must be exported and declared in that package's package block. Both halves of that sentence carry a failure shape of their own, covered in the next two sections: no import, and an imported name that is not exported — the math.pi case above is the second of those, with the qualifier present and the member's case wrong.

There is a form that makes the bare name legal. A dot import — import . "fmt" — brings the package's exported identifiers into the file's scope without a qualifier, and this program compiles and runs:

Go
// main.go
package main

import . "fmt"

func main() {
    Println("hi")
}
Terminal
$ go run main.go
hi

The output is hi. The form exists and works, and it is still not the fix to reach for by default: with the qualifier gone, a reader cannot tell which names in the file come from which package, and two dot-imported packages exporting the same name collide in the file's scope. Outside a few narrow settings — tests that need a package's names beside the package under test are the usual example — the qualified form is the repair. When this error appears in ordinary code, the missing qualifier, not a missing dot import, is the defect.

Missing import: the package name itself is undefined

Reverse the omission — keep the qualifier, drop the import — and the name that fails changes:

Go
// main.go
package main

func main() {
    fmt.Println("hi")
}
Terminal
$ go build
# example.com/undefined
./main.go:4:2: undefined: fmt

Now the message names fmt, at the start of the qualified identifier. The package name is not a declaration in the file until an import declaration puts it there: an import states that the source file depends on the imported package and enables access to its exported identifiers, and the import name is the identifier used for that access. Without it, fmt is one more undeclared name, and the compiler reports it exactly as it reports an undeclared variable — which is why this shape is worth separating. A reader scanning for a missing variable declaration will not find the problem; the missing line is an import, above the function, not a declaration inside it. The fix is import "fmt" in the file's import declaration, after which the qualified name resolves as a whole.

A renamed import produces the mirror image of the same shape. An import specification may give the package a different name for this file, and from that point the original name is not in scope:

Go
// main.go
package main

import f "fmt"

func main() {
    fmt.Println("hi")
    _ = f.Println
}
Terminal
$ go build
# example.com/undefined
./main.go:6:2: undefined: fmt

The import is present, the package is available, and the message still names fmt — because in this file the package's name is f, as the _ = f.Println line, which resolves without error, shows. The defect is not in the import's presence but in the qualifier's spelling relative to it. Either write the qualifier the import declares, f.Println, throughout the file, or remove the rename and let the package's default name stand. Renames earn their place when two imported paths end in the same package name, or when a package's name conflicts with a local name; a rename that nothing needed only manufactures this error for every reader who writes the natural qualifier.

Shadowing: the look-alike that prints nothing

One scope shape belongs in this guide precisely because it produces no message. An identifier declared in a block may be redeclared in an inner block, and while the inner declaration is in scope, the name denotes the inner entity:

Go
// main.go
package main

import "fmt"

func main() {
    x := 1
    {
        x := 2
        fmt.Println(x)
    }
    fmt.Println(x)
}
Terminal
$ go run main.go
2
1

The output is 2 and then 1. The inner := declared a new x, the inner print read that one, and at the closing brace the inner variable ended and the outer x, still holding 1, became visible again. No rule was broken and no error printed. This is the contrast to keep beside the scope-ending section: a use after a block fails loudly when the only declaration stood inside the block, and succeeds silently when an outer declaration also exists — silently, because the name after the block denotes the outer variable, which may not be the value the code inside the block was building. When a program compiles and a value is stale rather than missing, shadowing, not this guide's error, is the suspect — and giving the inner variable a name of its own is what makes the separation plain.

The fixed program

One program that applies each fix at once — every name declared before its use, in a scope that covers the use; the value that must outlive a statement kept in a variable declared outside the if statement that updates it; every package member reached through its qualifier, under the name its import declares; the exported spelling for the package constant; and the helper called from above its declaration, which package-level scope permits:

Go
// main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    totalCount := 3
    if bonus := 1; bonus > 0 {
        totalCount += bonus
    }
    fmt.Println(totalCount, math.Pi)
    fmt.Println(helper())
}

func helper() string {
    return "ready"
}
Terminal
$ go run main.go
4 3.141592653589793
ready

The output is 4 3.141592653589793 and then ready. The bonus variable is declared by the if initializer and used only inside that statement, where its scope runs. totalCount is declared in the function body, so the assignment inside the if writes the same variable the print after the statement reads, and the printed count is 4. math.Pi is the exported spelling, reached through the qualifier the import declares. And helper stands below main in the file, called without incident, because its scope is the package block rather than any position in the file.

The fixes, ranked

Declare the name before the use, in a scope that covers the use. This is the fix for the never-declared shape and for the use-before-declaration shape: one declaration, placed above the first use and in a block that encloses every use. A declaration placed inside a narrower block than the uses need trades this error for the scope-ending form of it.

Correct the spelling at the use to match the declaration. This is the fix for the typo and case shape. Compare the name in the message with the declared name character by character, including the case of the first letter. Never silence this shape by declaring the misspelled name; that creates a second variable and a program that compiles into the wrong answer.

Move the value out of the block when it must outlive the block. Declare before the if, for, or braced block and assign inside it. This is the fix for every scope-ending case, loop variables included: the declaration's block, not the statement that computes the value, decides how long the name lives.

Add the qualifier, and check the member's case. A function or constant that belongs to a package is written pkg.Name. This is the fix for the bare-Println shape and, with the exported spelling, for the math.pi shape — where the compiler's (but have Pi) hint names the correction outright.

Add the import, or write the qualifier the import declares. An unimported package name and a renamed package used under its old name print the identical message, undefined: fmt in the examples here, and are told apart by reading the import block: no import for the package means add one; an import with a different name means use that name, or drop the rename.

Which fix for which cause

What the code shows Cause Fix
A name with no declaration anywhere The declaration is missing Declare it before the use
A declaration spelled almost the same Typo or letter case differs Match the declared spelling
A package member in lowercase The member is exported in uppercase Use the exported spelling
A local use above its declaration Local scope starts at the declaration's end Move the declaration up
A declaration's own right side uses its name The name is not in scope yet there Compute from names already in scope
A use after a block or loop The scope ended with the block Declare before the block, assign inside
A bare package function name The qualifier is missing Write the qualified name
The package name in the message No import, or a renamed import Add the import, or use its name
No error, but a stale outer value An inner declaration shadows the outer Rename the inner variable

Checklist

  • Read the name in the message literally and compare it with the intended declaration character by character, case included, before changing anything. The spelling that failed is printed exactly; a near match is a different name.
  • Name the scope of the use and the scope of the declaration you expected. Same block, declaration first: the name should resolve, and the defect is spelling. Declaration later, or in an inner block, or at local level where package level was assumed: the defect is scope or ordering, and no spelling change repairs it.
  • Check whether the name belongs to a package before declaring anything locally. A missing qualifier and a missing import both print this message, and a local declaration with a package function's name silences it by hiding the intent.
  • When the message names a package, read the import block before editing the function: is the package imported at all, and under what name?
  • When the program compiles but a value is wrong, stop looking for this error. A shadowed name resolves successfully; the defect there is which declaration the name resolved to.

Sources

  • The Go Programming Language Specification — for scope (Go is lexically scoped using blocks; the scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec — the ShortVarDecl for a short variable declaration — and ends at the end of the innermost containing block; the scope of an identifier declared in the package block is the entire package block; an identifier declared in a block may be redeclared in an inner block, and while the inner declaration is in scope it denotes the entity declared by the inner declaration), for qualified identifiers (an identifier qualified with a package name prefix; a qualified identifier accesses an identifier in a different package, which must be imported, and the identifier must be exported and declared in the package block of that package), and for import declarations (an import declaration states that the source file depends on the imported package and enables access to its exported identifiers; the import names an identifier to be used for access and a path that specifies the package).
  • Effective Go — for naming and visibility in practice: the convention that an identifier beginning with an uppercase letter is exported and visible outside its package, and the worked examples of qualified package names in ordinary programs.

Keep Exploring