safe.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. Copyright 2024 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package safe
  14. // Field takes a pointer to any value (which may or may not be nil) and a
  15. // function that traverses to a target type R (a typical use case is to
  16. // dereference a field), and returns the result of the traversal, or the zero
  17. // value of the target type.
  18. //
  19. // This is roughly equivalent to:
  20. //
  21. // value != nil ? fn(value) : zero-value
  22. //
  23. // ...in languages that support the ternary operator.
  24. func Field[V any, R any](value *V, fn func(*V) R) R {
  25. if value == nil {
  26. var zero R
  27. return zero
  28. }
  29. o := fn(value)
  30. return o
  31. }
  32. // Cast takes any value, attempts to cast it to T, and returns the T value if
  33. // the cast is successful, or else the zero value of T.
  34. func Cast[T any](value any) T {
  35. result, _ := value.(T)
  36. return result
  37. }
  38. // Value takes a pointer to any value (which may or may not be nil) and a
  39. // function that returns a pointer to the same type. If the value is not nil,
  40. // it is returned, otherwise the result of the function is returned.
  41. //
  42. // This is roughly equivalent to:
  43. //
  44. // value != nil ? value : fn()
  45. //
  46. // ...in languages that support the ternary operator.
  47. func Value[T any](value *T, fn func() *T) *T {
  48. if value != nil {
  49. return value
  50. }
  51. return fn()
  52. }