Skip to content
undefined: ...

undefined: ...

DodaTech 3 min read

The “undefined: …” error in Go means the compiler cannot find a variable, function, type, or constant with the name you used. This is a compile-time error that prevents your program from building until the identifier is properly defined or imported.

What It Means

Go is a statically typed language with strict compile-time checks. Every identifier must be declared before it is used. When the compiler encounters a name it has never seen in the current scope, it stops with “undefined: …” followed by the missing name.

Why It Happens

  • You typed a variable or function name incorrectly (typo).
  • The variable or function is defined in a different scope and is not accessible.
  • You forgot to import the package that contains the identifier.
  • The function or variable is defined after it is used (Go does not hoist declarations).
  • You are trying to use an unexported name from another package.
  • The identifier was removed during refactoring but references were not updated.

How to Fix It

1. Check for typos

Compare your usage with the definition:

// Typo — will cause "undefined: fmtPrintln"
fmtPrintln("Hello")

// Fix — use the correct name
fmt.Println("Hello")

2. Ensure the identifier is defined in the correct scope

Variables defined inside a function are not visible to other functions:

func main() {
    message := "Hello"
    printMessage()
}

func printMessage() {
    // This will cause "undefined: message"
    fmt.Println(message)
}

// Fix: pass the variable as a parameter
func printMessage(msg string) {
    fmt.Println(msg)
}

3. Add missing imports

If the undefined identifier belongs to another package, you need to import it:

import "fmt"

func main() {
    // Without "fmt" imported, this causes "undefined: fmt"
    fmt.Println("Hello")
}

4. Check exported vs unexported names

Only names starting with a capital letter are accessible from other packages:

package utils

// unexported — not visible to other packages
var helper = "value"

// exported — visible to other packages
var Helper = "value"

5. Declare variables before use

Unlike some languages, Go does not allow forward references:

// This causes "undefined: y"
x := y + 1
y := 10

// Fix: declare y first
y := 10
x := y + 1

FAQ

Why does Go report 'undefined' for a function I defined in the same file?
Ensure the function is spelled identically when called, is not inside a different package, and that you are not calling it before the package declaration or inside a string literal. Scope issues are the most common cause.
Does Go hoist variable declarations like JavaScript?
No. Go does not hoist any declarations. Variables and functions must be declared before they are used in the source file. This is a deliberate design choice to make code easier to read and reason about.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro