]> Cypherpunks.ru repositories - gostls13.git/commitdiff
flag: recognize "0s" as the zero value for a flag.Duration
authorIan Lance Taylor <iant@golang.org>
Tue, 31 May 2016 18:23:50 +0000 (11:23 -0700)
committerIan Lance Taylor <iant@golang.org>
Tue, 31 May 2016 23:45:47 +0000 (23:45 +0000)
Implemented by using a reflect-based approach to recognize the zero
value of any non-interface type that implements flag.Value.  Interface
types will fall back to the old code.

Fixes #15904.

Change-Id: I594c3bfb30e9ab1aca3e008ef7f70be20aa41a0b
Reviewed-on: https://go-review.googlesource.com/23581
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
src/flag/flag.go
src/flag/flag_test.go

index 6acbbcd321b9eb56233df915101aa54e573ea558..fa0f05e96830128cdb2e8aac2a991c730f358ba2 100644 (file)
@@ -68,6 +68,7 @@ import (
        "fmt"
        "io"
        "os"
+       "reflect"
        "sort"
        "strconv"
        "time"
@@ -378,7 +379,21 @@ func Set(name, value string) error {
 
 // isZeroValue guesses whether the string represents the zero
 // value for a flag. It is not accurate but in practice works OK.
-func isZeroValue(value string) bool {
+func isZeroValue(flag *Flag, value string) bool {
+       // Build a zero value of the flag's Value type, and see if the
+       // result of calling its String method equals the value passed in.
+       // This works unless the Value type is itself an interface type.
+       typ := reflect.TypeOf(flag.Value)
+       var z reflect.Value
+       if typ.Kind() == reflect.Ptr {
+               z = reflect.New(typ.Elem())
+       } else {
+               z = reflect.Zero(typ)
+       }
+       if value == z.Interface().(Value).String() {
+               return true
+       }
+
        switch value {
        case "false":
                return true
@@ -449,7 +464,7 @@ func (f *FlagSet) PrintDefaults() {
                        s += "\n    \t"
                }
                s += usage
-               if !isZeroValue(flag.DefValue) {
+               if !isZeroValue(flag, flag.DefValue) {
                        if _, ok := flag.Value.(*stringValue); ok {
                                // put quotes on the value
                                s += fmt.Sprintf(" (default %q)", flag.DefValue)
index 1a8bdc106ac0554ef021adb946837396ecdb7008..e2319ec94c8691f83c30b0c9e9fdeb73903d2e13 100644 (file)
@@ -393,7 +393,7 @@ const defaultOutput = `  -A for bootstrapping, allow 'any' type
   -Z int
        an int that defaults to zero
   -maxT timeout
-       set timeout for dial (default 0s)
+       set timeout for dial
 `
 
 func TestPrintDefaults(t *testing.T) {