Skip to content

Instantly share code, notes, and snippets.

@jpillora
Created November 2, 2022 00:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jpillora/e370d969d3ba2ed8349fded11f0a1dea to your computer and use it in GitHub Desktop.
Save jpillora/e370d969d3ba2ed8349fded11f0a1dea 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