1 // Copyright 2016 Google LLC
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 // Package optional provides versions of primitive types that can
16 // be nil. These are useful in methods that update some of an API object's
27 // Bool is either a bool or nil.
30 // String is either a string or nil.
33 // Int is either an int or nil.
36 // Uint is either a uint or nil.
39 // Float64 is either a float64 or nil.
42 // Duration is either a time.Duration or nil.
46 // ToBool returns its argument as a bool.
47 // It panics if its argument is nil or not a bool.
48 func ToBool(v Bool) bool {
56 // ToString returns its argument as a string.
57 // It panics if its argument is nil or not a string.
58 func ToString(v String) string {
66 // ToInt returns its argument as an int.
67 // It panics if its argument is nil or not an int.
68 func ToInt(v Int) int {
76 // ToUint returns its argument as a uint.
77 // It panics if its argument is nil or not a uint.
78 func ToUint(v Uint) uint {
86 // ToFloat64 returns its argument as a float64.
87 // It panics if its argument is nil or not a float64.
88 func ToFloat64(v Float64) float64 {
96 // ToDuration returns its argument as a time.Duration.
97 // It panics if its argument is nil or not a time.Duration.
98 func ToDuration(v Duration) time.Duration {
99 x, ok := v.(time.Duration)
101 doPanic("Duration", v)
106 func doPanic(capType string, v interface{}) {
107 panic(fmt.Sprintf("optional.%s value should be %s, got %T", capType, strings.ToLower(capType), v))