Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go: import cycle not allowed

Go forbids cycles in the package import graph. Break them by extracting shared types, declaring interfaces where consumed, or inverting init registration.

~5 min readGo
#go#packages#imports#architecture
Go package graph with two crates pointing at each other and a shared types crate breaking the loop

Introduction & Quick Summary

The build refuses the package graph before compiling a single line:

code
package example.com/app/store imports example.com/app/models imports example.com/app/store import cycle not allowed

Quick answer: Go forbids cycles in the package import graph at any depth. Two packages cannot import each other, directly or through a chain of others. Break the cycle by moving the shared types into a third package, or by having the lower-level package declare the interface it needs instead of importing the higher-level one.

go
// before: store -> models -> store // after: both depend on a small shared package // internal/domain/order.go package domain type Order struct{ ID string }
go
// internal/store/store.go package store import "example.com/app/internal/domain" type Store interface{ Save(domain.Order) error }
go
// the caller wires the implementation package main import ( "example.com/app/internal/domain" "example.com/app/internal/store" ) var _ store.Store = memoryStore{}

The message lists the full chain, so the first job is reading it: the cycle is the loop in that list, not necessarily the two packages named first. This guide covers the four ways to break one, what each costs, and the test-only and interface-related cases where the message appears for a package set you thought was acyclic.

Core Mechanics, Signatures & Reproducible Setup

A Go program is a directed acyclic graph of packages. The compiler builds that graph from import paths and refuses it if it contains a cycle, because initialization order across a cycle cannot be defined.

A three-package reproduction:

bash
mkdir -p cycle/app/store cycle/app/models && cd cycle go mod init example.com/app cat > app/models/order.go <<'GO' package models import "example.com/app/store" type Order struct{ ID string } func (o Order) Save(s *store.Store) error { return s.Save(o) } GO cat > app/store/store.go <<'GO' package store import "example.com/app/models" type Store struct{} func (s *Store) Save(o models.Order) error { return nil } GO go build ./... # package example.com/app/models # imports example.com/app/store # imports example.com/app/models # import cycle not allowed

The graph is checked per package, not per file: splitting types across files in the same directory changes nothing. Two facts follow from that:

  • A cycle can be long — a → b → c → a — and the reported chain is the shortest path the loader found.
  • Test files can create a cycle that the normal build does not, which is why the message sometimes contains [test] or names a _test package.
bash
# trace what a package actually depends on go list -deps ./app/store | head -20 go list -f '{{.ImportPath}} -> {{join .Imports " "}}' ./...

Key Comparison Table

Message shapeCauseFix
a imports b imports a: import cycle not allowedmutual importsextract or invert
import cycle not allowed in testtest package imports a package that imports the tested oneuse package foo_test
import cycle not allowed; importing X from Ygenerated file imports a package that imports its generatormove generated code
cycle through mainlibrary imports the command packagemove shared code to internal
cycle only for one build tagtag-specific file imports upwardmove the tagged code down
Cycle-breaking strategyCostUse when
extract shared types to a new packageone more packageboth sides need the same data shape
consumer declares the interfaceduplicated small interfacesthe dependency is behaviour, not data
invert with callbacks or registrationindirection at startupthe cycle exists for init() side effects
merge the packagesa larger packagethe split was accidental
move to internal/ subpackageimport path churnboundaries should be enforced
Go tooling commandWhat it answers
go list -deps ./...full dependency list
go list -f '{{.ImportPath}} {{join .Deps "\n"}}'per-package dependency tree
go mod graphmodule-level requirements, not package cycles
go vet ./...unused or wrong imports that often accompany a refactor

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Read the chain, then choose the cut

The chain tells you which edge to remove. Prefer cutting the edge where the dependency is weakest — usually the one that only exists for a type definition:

go
// models imports store only to call Save func (o Order) Save(s *store.Store) error // better: keep the behaviour on the store side // store.Save(Order) — models no longer imports store

A method that exists only to save itself is the usual reason a domain package grows a dependency on persistence.

2. Extract the shared shape

When both packages genuinely need the same structure, a third package that neither owns is the cleanest fix. Name it for the domain concept, not for the layer:

go
// internal/domain/order.go package domain type Order struct { ID string Amount int64 }
go
// internal/store/store.go package store import "example.com/app/internal/domain" type Repo struct{} func (r *Repo) Save(o domain.Order) error { return nil }
go
// internal/api/handler.go package api import ( "example.com/app/internal/domain" "example.com/app/internal/store" ) type Handler struct{ Repo *store.Repo } func (h *Handler) Create(o domain.Order) error { return h.Repo.Save(o) }

The domain package imports nothing from the other two, so the graph stays acyclic as the application grows.

3. Declare the interface where it is used

Go interfaces are satisfied implicitly, so the consumer can define what it needs without importing the implementation. This is the standard answer when the cycle is caused by a concrete type crossing layers:

go
// internal/api/handler.go package api type Saver interface{ Save(orderID string, amount int64) error } type Handler struct{ saver Saver } // internal/store/store.go does not import api; it just implements the method set

The interface is small, lives next to its user, and the wiring happens in main, which imports both.

4. Test cycles and the _test package suffix

A test in package store can import a helper that imports store, which produces import cycle not allowed in test. Move the test to the external form, which is why Go has two test package names:

go
// store_test.go package store_test // not "package store" import ( "testing" "example.com/app/internal/store" "example.com/app/internal/testutil" )

store_test is a separate package that imports store, so testutil may import store freely. The trade-off is that only the exported API is reachable.

5. Registration and init() cycles

Plugins often create a cycle because the plugin package needs the registry and the registry needs the plugin to register itself. Invert the flow: the registry exposes a function, and main imports the plugins and registers them, or a plugin package imports only the interface package:

go
// internal/plugin/registry.go package plugin type Plugin interface{ Name() string } var registry = map[string]Plugin{} func Register(p Plugin) { registry[p.Name()] = p }
go
// internal/plugin/jsonfmt/json.go package jsonfmt import "example.com/app/internal/plugin" type formatter struct{} func (formatter) Name() string { return "json" } func init() { plugin.Register(formatter{}) }
go
// main.go — the only place that imports both import ( _ "example.com/app/internal/plugin/jsonfmt" "example.com/app/internal/plugin" )

The blank import in main keeps the side effect without any package importing upward.

6. Cycles across module boundaries

A cycle can cross modules: module A requires module B while B requires A. Go reports it as a module error rather than a package one, and the same rules apply — either split the shared types into a third module, or move the dependency to one direction with interfaces. go mod graph shows module edges; if the cycle exists only at the module level but not in the package graph, the build succeeds, but the dependency direction is worth fixing before it becomes a package cycle. Reading a large diff of an import refactor is easier with the text diff tool, and a go.mod change is faster to verify with the JSON formatter when a dependency was replaced.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Splitting files instead of packages. A cycle is between import paths; moving a type to another file in the same directory does not help.
  • Putting the interface in the implementation package. It recreates the import direction you were trying to remove; define it where it is consumed.
  • Ignoring init()-only imports. A blank import for side effects still counts as an edge in the graph.
  • Importing the command package. main cannot be imported; move what it needs into a library package.
  • Assuming generics break cycles. Type parameters change signatures, not the import graph.
  • Version notes. The rule has not changed across Go 1.x; Go 1.21 and later report the chain with the imports lines shown above, and go list -deps remains the fastest way to inspect the graph. Module replace directives change which module is used, not whether a package cycle exists.

Official documentation: Import declarations and How to Write Go Code.

Official references

primary documentation

The Go documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.