reflect.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package sprig
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. // typeIs returns true if the src is the type named in target.
  7. // It compares the type name of src with the target string.
  8. //
  9. // Parameters:
  10. // - target: The type name to check against
  11. // - src: The value whose type will be checked
  12. //
  13. // Returns:
  14. // - bool: True if the type name of src matches target, false otherwise
  15. func typeIs(target string, src any) bool {
  16. return target == typeOf(src)
  17. }
  18. // typeIsLike returns true if the src is the type named in target or a pointer to that type.
  19. // This is useful when you need to check for both a type and a pointer to that type.
  20. //
  21. // Parameters:
  22. // - target: The type name to check against
  23. // - src: The value whose type will be checked
  24. //
  25. // Returns:
  26. // - bool: True if the type of src matches target or "*"+target, false otherwise
  27. func typeIsLike(target string, src any) bool {
  28. t := typeOf(src)
  29. return target == t || "*"+target == t
  30. }
  31. // typeOf returns the type of a value as a string.
  32. // It uses fmt.Sprintf with the %T format verb to get the type name.
  33. //
  34. // Parameters:
  35. // - src: The value whose type name will be returned
  36. //
  37. // Returns:
  38. // - string: The type name of src
  39. func typeOf(src any) string {
  40. return fmt.Sprintf("%T", src)
  41. }
  42. // kindIs returns true if the kind of src matches the target kind.
  43. // This checks the underlying kind (e.g., "string", "int", "map") rather than the specific type.
  44. //
  45. // Parameters:
  46. // - target: The kind name to check against
  47. // - src: The value whose kind will be checked
  48. //
  49. // Returns:
  50. // - bool: True if the kind of src matches target, false otherwise
  51. func kindIs(target string, src any) bool {
  52. return target == kindOf(src)
  53. }
  54. // kindOf returns the kind of a value as a string.
  55. // The kind represents the specific Go type category (e.g., "string", "int", "map", "slice").
  56. //
  57. // Parameters:
  58. // - src: The value whose kind will be returned
  59. //
  60. // Returns:
  61. // - string: The kind of src as a string
  62. func kindOf(src any) string {
  63. return reflect.ValueOf(src).Kind().String()
  64. }