ensure.go 358 B

123456789101112131415
  1. package ensure
  2. type EnsureFunc[T any] func() T
  3. // Ensure ensures that the returned value is not nil.
  4. // If the provided pointer is nil, the function calls the provided
  5. // EnsureFunc to obtain a new value.
  6. // Otherwise, it returns the original value.
  7. func Ensure[T any](val *T, f EnsureFunc[T]) *T {
  8. if val == nil {
  9. v := f()
  10. return &v
  11. }
  12. return val
  13. }