Go Idioms

Make the Zero Value Useful

Use a boolean flag to lazily initialize internal state on first use, ensuring the zero value is valid and safe to use immediately.

Make the zero value useful by initializing internal state lazily on first use rather than requiring explicit construction. In the gmp package, the Int struct uses an init boolean flag to track if the underlying C mpz_t has been initialized, and the doinit method calls C.mpz_init only if the flag is false.

type Int struct {
	i    C.mpz_t
	init bool
}

func (z *Int) doinit() {
	if z.init {
		return
	}
	z.init = true
	C.mpz_init(&z.i[0])
}

This ensures that var x Int creates a valid zero value (representing 0) without crashing, bridging the gap between Go's zero-value convention and C libraries that require explicit initialization.