2020-09-02 22:38:26 +02:00
|
|
|
// Package nodefault provides newtypes around builtin Go types
|
|
|
|
// so that if the newtype is used as a field in a struct and that field
|
|
|
|
// is zero-initialized (https://golang.org/ref/spec#The_zero_value),
|
|
|
|
// accessing the field will cause a null pointer deref panic.
|
|
|
|
// Or in other terms: It soft-enforces that the caller sets the field
|
|
|
|
// explicitly when constructing the struct.
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
2022-10-24 22:09:02 +02:00
|
|
|
// type Config struct {
|
|
|
|
// // This field must be set to a non-nil value,
|
|
|
|
// // forcing the caller to make their mind up
|
|
|
|
// // about this field.
|
|
|
|
// CriticalSetting *nodefault.Bool
|
|
|
|
// }
|
2020-09-02 22:38:26 +02:00
|
|
|
//
|
|
|
|
// An function that takes such a Config should _not_ check for nil-ness:
|
|
|
|
// and instead unconditionally dereference:
|
|
|
|
//
|
2022-10-24 22:09:02 +02:00
|
|
|
// func f(c Config) {
|
|
|
|
// if (c.CriticalSetting) { }
|
|
|
|
// }
|
2020-09-02 22:38:26 +02:00
|
|
|
//
|
|
|
|
// If the caller of f forgot to specify the .CriticalSetting
|
|
|
|
// field, the Go runtime will issue a nil-pointer deref panic
|
|
|
|
// and it'll be clear that the caller did not read the docs of Config.
|
|
|
|
//
|
2022-10-24 22:09:02 +02:00
|
|
|
// f(Config{}) // crashes
|
2020-09-02 22:38:26 +02:00
|
|
|
//
|
2022-10-24 22:09:02 +02:00
|
|
|
// f Config{ CriticalSetting: &nodefault.Bool{B: false}} // doesn't crash
|
2020-09-02 22:38:26 +02:00
|
|
|
package nodefault
|