go
build_error
ai_generated
true
import cycle not allowed package A imports B imports A
ID: go/missing-import-cycle-with-init
85%Fix Rate
90%Confidence
1Evidence
2023-07-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| go1.20 | active | — | — | — |
| go1.21 | active | — | — | — |
| go1.22 | active | — | — | — |
Root Cause
Two or more packages import each other directly or indirectly, creating a circular dependency that Go's compiler cannot resolve.
generic中文
两个或多个包直接或间接相互导入,创建了 Go 编译器无法解析的循环依赖。
Official Documentation
https://go.dev/ref/spec#Import_declarationsWorkarounds
-
90% success Extract the shared types or interfaces into a third package that both A and B import
Extract the shared types or interfaces into a third package that both A and B import
-
85% success Use dependency injection: pass interfaces from A to B instead of importing A directly in B
Use dependency injection: pass interfaces from A to B instead of importing A directly in B
中文步骤
Extract the shared types or interfaces into a third package that both A and B import
Use dependency injection: pass interfaces from A to B instead of importing A directly in B
Dead Ends
Common approaches that don't work:
-
Using a blank import (_ "package") to break the cycle
95% fail
Blank imports only trigger init() functions, they don't resolve the circular dependency in the type system.
-
Moving all code into a single package
80% fail
Violates separation of concerns; makes the codebase monolithic and harder to maintain.
-
Adding a new import that re-exports types from the cycle
90% fail
Creates a longer cycle or introduces a third package that still depends on the cycle.