var period = flag.Duration("period", 1*time.Second, "sleep period")funcmain() { flag.Parse() fmt.Printf("Sleeping for %v...", *period) time.Sleep(*period) fmt.Println()}
// CelsiusFlag defines a Celsius flag with the specified name,// default value, and usage, and returns the address of the flag variable.// The flag argument must have a quantity and a unit, e.g., "100C".funcCelsiusFlag(name string, value Celsius, usage string) *Celsius { f :=celsiusFlag{value} flag.CommandLine.Var(&f, name, usage)return&f.Celsius}
现在我们可以开始在我们的程序中使用新的标记:
gopl.io/ch7/tempflag
var temp = tempconv.CelsiusFlag("temp", 20.0, "the temperature")funcmain() { flag.Parse() fmt.Println(*temp)}
下面是典型的场景:
$ go build gopl.io/ch7/tempflag
$ ./tempflag
20°C
$ ./tempflag -temp -18C
-18°C
$ ./tempflag -temp 212°F
100°C
$ ./tempflag -temp 273.15K
invalid value "273.15K" for flag -temp: invalid temperature "273.15K"
Usage of ./tempflag:
-temp value
the temperature (default 20°C)
$ ./tempflag -help
Usage of ./tempflag:
-temp value
the temperature (default 20°C)