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.
// 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)
}
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.
// 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"])
}
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.
Sign in to keep your read marks on every device. Sign in
Was this helpful?