Skip to content

Instantly share code, notes, and snippets.

@TrooperT
Forked from jpillora/type-cache.go
Created April 12, 2023 18:23
Show Gist options
  • Select an option

  • Save TrooperT/103eef82acb276193b7e129b86e7ca45 to your computer and use it in GitHub Desktop.

Select an option

Save TrooperT/103eef82acb276193b7e129b86e7ca45 to your computer and use it in GitHub Desktop.
func typeCache[T any](compute func(t reflect.Type) T) func(t reflect.Type) T {
cache := map[reflect.Type]T{}
return func(t reflect.Type) T {
if v, ok := cache[t]; ok {
return v
}
v := compute(t) // but compute cant recurse
cache[t] = v
return v
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment