optional.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright 2016 Google Inc. All Rights Reserved.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package optional provides versions of primitive types that can
  15. // be nil. These are useful in methods that update some of an API object's
  16. // fields.
  17. package optional
  18. import (
  19. "fmt"
  20. "strings"
  21. )
  22. type (
  23. // Bool is either a bool or nil.
  24. Bool interface{}
  25. // String is either a string or nil.
  26. String interface{}
  27. // Int is either an int or nil.
  28. Int interface{}
  29. // Uint is either a uint or nil.
  30. Uint interface{}
  31. // Float64 is either a float64 or nil.
  32. Float64 interface{}
  33. )
  34. // ToBool returns its argument as a bool.
  35. // It panics if its argument is nil or not a bool.
  36. func ToBool(v Bool) bool {
  37. x, ok := v.(bool)
  38. if !ok {
  39. doPanic("Bool", v)
  40. }
  41. return x
  42. }
  43. // ToString returns its argument as a string.
  44. // It panics if its argument is nil or not a string.
  45. func ToString(v String) string {
  46. x, ok := v.(string)
  47. if !ok {
  48. doPanic("String", v)
  49. }
  50. return x
  51. }
  52. // ToInt returns its argument as an int.
  53. // It panics if its argument is nil or not an int.
  54. func ToInt(v Int) int {
  55. x, ok := v.(int)
  56. if !ok {
  57. doPanic("Int", v)
  58. }
  59. return x
  60. }
  61. // ToUint returns its argument as a uint.
  62. // It panics if its argument is nil or not a uint.
  63. func ToUint(v Uint) uint {
  64. x, ok := v.(uint)
  65. if !ok {
  66. doPanic("Uint", v)
  67. }
  68. return x
  69. }
  70. // ToFloat64 returns its argument as a float64.
  71. // It panics if its argument is nil or not a float64.
  72. func ToFloat64(v Float64) float64 {
  73. x, ok := v.(float64)
  74. if !ok {
  75. doPanic("Float64", v)
  76. }
  77. return x
  78. }
  79. func doPanic(capType string, v interface{}) {
  80. panic(fmt.Sprintf("optional.%s value should be %s, got %T", capType, strings.ToLower(capType), v))
  81. }