go build_error ai_generated true

import cycle not allowed package A imports B imports A

ID: go/missing-import-cycle-with-init

Also available as: JSON · Markdown · 中文
85%Fix Rate
90%Confidence
1Evidence
2023-07-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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_declarations

Workarounds

  1. 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
  2. 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

中文步骤

  1. Extract the shared types or interfaces into a third package that both A and B import
  2. Use dependency injection: pass interfaces from A to B instead of importing A directly in B

Dead Ends

Common approaches that don't work:

  1. 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.

  2. Moving all code into a single package 80% fail

    Violates separation of concerns; makes the codebase monolithic and harder to maintain.

  3. 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.