Common errors

Compile errors such as declared and not used and undefined, and runtime panics such as index out of range and nil map.

Runs in Zerethon IDE · Go 1.27 Official Go documentation ↗

Go reports most mistakes when it builds, before anything runs. A runtime failure is a panic: it prints panic: with the reason, then the stack of calls with file and line, and the program exits with status 2.

  • declared and not used: x — remove the variable or use it; assign to _ to discard a value on purpose.
  • "os" imported and not used — remove the import.
  • undefined: x — a typo, a variable declared in another block, or a function in a file that is not part of the build (a main* or test_* file).
  • cannot use x (variable of type int) as string value — convert explicitly: strconv.Itoa(x), float64(x).
  • missing return — every path through a function with a result type must return.
  • panic: runtime error: index out of range [3] with length 3 — indexes go from 0 to len(s)-1.
  • panic: assignment to entry in nil map — create the map with make or map[K]V{} first.
  • panic: runtime error: invalid memory address or nil pointer dereference — a pointer, map or interface is nil where a value was expected.
  • fatal error: all goroutines are asleep - deadlock! — every goroutine is waiting on a channel or lock that nothing will release.
main.go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	total := 0
	for _, v := range []string{"10", "x", "7"} {
		n, err := strconv.Atoi(v)
		if err != nil {
			fmt.Printf("skipped %q\n", v)
			continue
		}
		total += n
	}
	fmt.Println("total:", total)
}

Output

skipped "x"
total: 17
Handle an error you expect by checking the returned error, not by letting the program panic.