Initialization Loop

initialization loop: x refers to y, y refers to x

Quick Answer

Two package-level variables depend on each other for initialization. Break the cycle by using a function or lazy initialization.

Why This Happens

Go initializes package-level variables in dependency order. If variable A's initializer references B and B's initializer references A, Go cannot determine the initialization order and reports an error. Break the cycle by computing one value in an init() function.

The Problem

var a = b + 1
var b = a + 1 // initialization loop

The Fix

var a int
var b int

func init() {
    a = 1
    b = a + 1
}

Step-by-Step Fix

  1. 1

    Identify the loop

    Read the error to see which variables form the initialization cycle.

  2. 2

    Break the dependency

    Determine which variable should be initialized first.

  3. 3

    Use init() function

    Move one or both initializations into an init() function where you control the order.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free