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.

Introduction & Quick Summary
The build refuses the package graph before compiling a single line:
package example.com/app/store
imports example.com/app/models
imports example.com/app/store
import cycle not allowedQuick 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.
// before: store -> models -> store
// after: both depend on a small shared package
// internal/domain/order.go
package domain
type Order struct{ ID string }// internal/store/store.go
package store
import "example.com/app/internal/domain"
type Store interface{ Save(domain.Order) error }// 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:
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 allowedThe 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_testpackage.
# trace what a package actually depends on
go list -deps ./app/store | head -20
go list -f '{{.ImportPath}} -> {{join .Imports " "}}' ./...Key Comparison Table
| Message shape | Cause | Fix |
|---|---|---|
a imports b imports a: import cycle not allowed | mutual imports | extract or invert |
import cycle not allowed in test | test package imports a package that imports the tested one | use package foo_test |
import cycle not allowed; importing X from Y | generated file imports a package that imports its generator | move generated code |
cycle through main | library imports the command package | move shared code to internal |
| cycle only for one build tag | tag-specific file imports upward | move the tagged code down |
| Cycle-breaking strategy | Cost | Use when |
|---|---|---|
| extract shared types to a new package | one more package | both sides need the same data shape |
| consumer declares the interface | duplicated small interfaces | the dependency is behaviour, not data |
| invert with callbacks or registration | indirection at startup | the cycle exists for init() side effects |
| merge the packages | a larger package | the split was accidental |
move to internal/ subpackage | import path churn | boundaries should be enforced |
| Go tooling command | What it answers |
|---|---|
go list -deps ./... | full dependency list |
go list -f '{{.ImportPath}} {{join .Deps "\n"}}' | per-package dependency tree |
go mod graph | module-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:
// 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 storeA 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:
// internal/domain/order.go
package domain
type Order struct {
ID string
Amount int64
}// 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 }// 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:
// 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 setThe 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:
// 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:
// internal/plugin/registry.go
package plugin
type Plugin interface{ Name() string }
var registry = map[string]Plugin{}
func Register(p Plugin) { registry[p.Name()] = p }// 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{}) }// 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.
maincannot 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
importslines shown above, andgo list -depsremains the fastest way to inspect the graph. Modulereplacedirectives change which module is used, not whether a package cycle exists.
Official documentation: Import declarations and How to Write Go Code.
Official references
primary documentationThe Go documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo: x509 certificate signed by unknown authority
Go cannot build a chain to a trusted root: no CA bundle in the image, a private CA, or a missing intermediate. Install roots or set RootCAs.
Go: fatal error: concurrent map writes in goroutines
The runtime catches two writes to one map and stops the process. Guard access with a mutex, use sync.Map for caches, or give one owner.
Go: go.mod file not found in current directory
Go 1.16 and later build in module mode. Run commands inside the module root, create a go.mod with go mod init, or set GO111MODULE and GOWORK deliberately.
Go: http: superfluous response.WriteHeader call
net/http logs this when a handler writes the status twice. It almost always marks a later status write that was silently ignored, or no return.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.