cmpx.go 654 B

12345678910111213141516171819202122
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package cmpx has code that will likely land in a future version of Go, but
  4. // we want sooner.
  5. package cmpx
  6. // Or returns the first non-zero element of list, or else returns the zero T.
  7. //
  8. // This is the proposal from
  9. // https://github.com/golang/go/issues/60204#issuecomment-1581245334.
  10. func Or[T comparable](list ...T) T {
  11. // TODO(bradfitz): remove the comparable constraint so we can use this
  12. // with funcs too and use reflect to see whether they're non-zero? 🤷‍♂️
  13. var zero T
  14. for _, v := range list {
  15. if v != zero {
  16. return v
  17. }
  18. }
  19. return zero
  20. }