golang/go · error

cannot import "main"

Error message

cannot import "main"

What it means

Thrown by resolveImportPath when the import path is literally "main". The path "main" is reserved to identify the program's main package, just as "math" identifies the standard math package; it cannot be imported as a dependency.

Source

Thrown at src/cmd/compile/internal/noder/import.go:133

		if file, err := os.Open(fmt.Sprintf("%s/pkg/%s_%s%s/%s.a", buildcfg.GOROOT, buildcfg.GOOS, buildcfg.GOARCH, suffix, path)); err == nil {
			return file, nil
		}
		if file, err := os.Open(fmt.Sprintf("%s/pkg/%s_%s%s/%s.o", buildcfg.GOROOT, buildcfg.GOOS, buildcfg.GOARCH, suffix, path)); err == nil {
			return file, nil
		}
	}
	return nil, errors.New("file not found")
}

// resolveImportPath resolves an import path as it appears in a Go
// source file to the package's full path.
func resolveImportPath(path string) (string, error) {
	// The package name main is no longer reserved,
	// but we reserve the import path "main" to identify
	// the main package, just as we reserve the import
	// path "math" to identify the standard math package.
	if path == "main" {
		return "", errors.New("cannot import \"main\"")
	}

	if base.Ctxt.Pkgpath == "" {
		panic("missing pkgpath")
	}
	if path == base.Ctxt.Pkgpath {
		return "", fmt.Errorf("import %q while compiling that package (import cycle)", path)
	}

	if mapped, ok := base.Flag.Cfg.ImportMap[path]; ok {
		path = mapped
	}

	if islocalname(path) {
		if path[0] == '/' {
			return "", errors.New("import path cannot be absolute path")
		}

View on GitHub (pinned to b6b368adc5)

Solutions

  1. Remove or rename the import; you cannot import another package whose import path is "main".
  2. If you intended to share code, move that code into a package with a non-reserved import path.
  3. Audit code generators or import maps that may rewrite a path to "main".

Example fix

// before
import "main"
// after (move shared code into a real package)
import "example.com/myproject/appmain"
Defensive patterns

Strategy: validation

Validate before calling

// Reject attempts to import the reserved path "main".
func isReservedImport(p string) bool { return p == "main" }

Prevention

When it happens

Trigger: A source file contains `import "main"` (or an import map resolves a path to "main"). resolveImportPath checks path=="main" before any further resolution.

Common situations: A typo or auto-generated import referencing a package whose import path was set to "main"; tooling/codegen producing `import "main"`; confusion between package name `main` (allowed as a name) and import path "main" (reserved).

Related errors


AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12). Data as JSON: /api/errors/e5dbe364d63fadcd. Report an issue: GitHub.