October 2015
Beginner to intermediate
400 pages
14h 44m
English
sync.Once
It is good practice to defer an expensive initialization step until
the moment it is needed.
Initializing a variable up front increases the
start-up latency of a program and is unnecessary if execution
doesn’t always reach the part of the program that uses that variable.
Let’s return to the icons variable we saw earlier in the chapter:
var icons map[string]image.Image
This version of Icon uses lazy initialization:
func loadIcons() { icons = map[string]image.Image{ "spades.png": loadIcon("spades.png"), "hearts.png": loadIcon("hearts.png"), "diamonds.png": loadIcon("diamonds.png"), "clubs.png": loadIcon("clubs.png"), } } // NOTE: not concurrency-safe! ...