geektutu/7days-golang · error

nil Getter

Error message

nil Getter

What it means

Same "nil Getter" panic as errors 90/92/94, in the day6-single-flight version: NewGroup rejects a nil getter because the Group needs a loader to resolve cache misses. The panic fails fast at construction time.

Source

Thrown at gee-cache/day6-single-flight/geecache/geecache.go:42

}

// A GetterFunc implements Getter with a function.
type GetterFunc func(key string) ([]byte, error)

// Get implements Getter interface function
func (f GetterFunc) Get(key string) ([]byte, error) {
	return f(key)
}

var (
	mu     sync.RWMutex
	groups = make(map[string]*Group)
)

// NewGroup create a new instance of Group
func NewGroup(name string, cacheBytes int64, getter Getter) *Group {
	if getter == nil {
		panic("nil Getter")
	}
	mu.Lock()
	defer mu.Unlock()
	g := &Group{
		name:      name,
		getter:    getter,
		mainCache: cache{cacheBytes: cacheBytes},
		loader:    &singleflight.Group{},
	}
	groups[name] = g
	return g
}

// GetGroup returns the named group previously created with NewGroup, or
// nil if there's no such group.
func GetGroup(name string) *Group {
	mu.RLock()
	g := groups[name]

View on GitHub (pinned to cf36443821)

Solutions

  1. Provide a real Getter via geecache.GetterFunc or a struct implementing Getter
  2. Fix initialization ordering so the data source exists before group creation
  3. Add a constructor wrapper that validates the getter in your own code

Example fix

// before
geecache.NewGroup("scores", 2<<20, nil) // panic
// after
geecache.NewGroup("scores", 2<<20, geecache.GetterFunc(func(key string) ([]byte, error) {
    return slowDBLookup(key)
}))
Defensive patterns

Strategy: validation

Validate before calling

if getter == nil {
    panic("NewGroup requires a non-nil Getter")
}
g := geecache.NewGroup("scores", 2<<20, getter)

Type guard

func hasLoader(g geecache.Getter) bool { return g != nil }

Try / catch

// Handle at process startup, not per call:
defer func() {
    if r := recover(); r != nil { log.Fatalf("group creation panicked: %v", r) }
}()

Prevention

When it happens

Trigger: Passing nil (or a typed-nil interface) as the third argument to geecache.NewGroup.

Common situations: Getter wired to a service not yet initialized; refactoring removed the assignment; test scaffolding passing nil to satisfy the signature.

Related errors


AI-assisted analysis of geektutu/7days-golang@cf36443821 (2026-09-03). Data as JSON: /api/errors/a6758ea2aba40004. Report an issue: GitHub.