← Runtimes
Runtimes

Imports, dependencies, and initialization

When startup code runs, in what order, and how often.

Separate dependency availability from initialized data.

Outcome

Predict when, in what order and how often startup values initialize in the selected language, and make a value that depends on later work initialize lazily, once.

Terminology (4)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Initialization
Giving a variable its first value. Startup values are initialized before or during the program’s first use of them.
Lazy initialization
Building a value the first time it is read, then reusing it.
Initialization order
The order in which a language runs startup initializers.
init function
A Go function named init that runs after the package’s variables are initialized and before main.

Dependencies and readiness are different questions

A dependency lets code refer to another unit’s names or values. Initialization establishes the values that running code will use. These are related operations with different language rules: finding a name does not by itself establish that every piece of setup on which its value depends has completed.

Eager initialization performs setup before a later use needs it; lazy initialization defers work until a use requests it. Retaining that result avoids rebuilding it, but also retains the inputs used at construction. For a derived table, ask both when its inputs are ready and how long the resulting table remains valid. The examples isolate these decisions using each language’s startup and first-use mechanisms.

01Order

Which startup value is ready first?

A shipping-rate helper is moving out of the checkout startup code. It must still quote from the configured base rates, and merchants can override zones before quotes begin. Which work can happen when a dependency loads, and which work must wait until those settings are complete?

Start with the helper’s smallest dependency: a surcharge that is 20% of a 500-cent base rate. Both values are fixed for this probe, but surcharge is declared first. If moving the setup changes when it runs, can the surcharge still see a ready base rate? These single-file programs isolate that question; they do not trace a real multi-file loader.

An imported Go package initializes before the package importing it. Within this package, variables initialize by dependencies determined from references, including references in function bodies; init functions run after the variables, then main. These rules do not make code in a later init function run early.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A shipping-rate service's two package-level variables, declared in the opposite order to their dependency.
package main

import "fmt"

func build(name string, value func() int) int {
	fmt.Println("making", name)

	return value()
}

// Cents per parcel: the surcharge is 20% of the base rate.
var surcharge = build("surcharge", func() int { return baseRate * 20 / 100 })
var baseRate = build("base rate", func() int { return 500 })

func init() {
	fmt.Println("init")
}

func main() {
	fmt.Println("main: surcharge =", surcharge)
}
What does go run print?
Go · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
go run .

Put each example in the shown file and run the command. The TypeScript command checks with tsc first; the first example passes the checker and fails only when it runs.

02Once

How do you build something at first use?

The helper also owns a rate table shared by successive quotes. Recomputing it at every lookup would repeat setup; constructing it while loading the helper would run setup even when no quote needs it. First isolate how to build and retain a table on demand. This fixed-rate probe has no merchant overrides yet.

sync.OnceValue constructs a wrapper at package initialization. The wrapped builder runs on the wrapper’s first call; subsequent calls share its result, including concurrent callers. That does not make later map mutation safe.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A rate table built the first time a quote needs it, then reused.
package main

import (
	"fmt"
	"sync"
)

var rates = sync.OnceValue(func() map[string]int {
	fmt.Println("building the table")

	return map[string]int{"A": 250}
})

func main() {
	fmt.Println("main starts")
	fmt.Println(rates()["A"])
	fmt.Println(rates()["A"])
}
The program looks up zone A’s rate twice. Where does building the table print?

03Hidden dependencies

When is the configured table ready?

Now add the merchant’s settings. The service starts with built-in zones, applies all zone additions and overrides, then accepts quotes. Express quotes use a separate table derived at 140% of each base rate. A reference to the base table says where to read; it does not say that these configuration writes have finished. Explicit call order can establish that boundary.

The shown initialization rule does not complete later configuration for you
LanguageStartup values are initializedA readiness condition the rule does not establish
TypeScriptIn source order, once per moduleA table filled by a later statement or by code in main
GoVariables in dependency order, then init functionsA map filled by init and read by a variable initializer
RustLazyLock closure on first access; wrapper constructed by a constant initializerFirst access does not promise that later configuration writes have happened
C++Static initialization, then applicable dynamic-initialization ordering rulesA later configuration write is not forced merely by referring to its target
West’s base rate is 600 cents. The service builds a separate express table at 140%, then replaces West’s base rate with 800 cents without rebuilding that table. What does the first express lookup return?

04Practice

Finish the shipping-rate service

Complete the helper in a reduced shipping-rate process. Initialize the built-in table through its supplied row builder, make express rates use ready inputs, then accept merchant overrides without repeating the derived-table build for every quote. All zone lines precede every quote, and this process supports no settings changes after quoting begins. The supplied rates produce whole-cent express quotes; rounding policy is outside this startup probe. Each level supplies the parts that already work.

The shipping-rate service

Prepare built-in rates, respect native initialization, then cache the completed configuration on demand.

  1. easy · R-INIT-V4-1 Prepare the rate table
  2. medium · R-INIT-V4-2 Prepare the express table
  3. hard · R-INIT-V4-3 Build the express table once
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.