-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
45 lines (38 loc) · 1.09 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
"flag"
"fmt"
tempconv "github.com/jez321/gopl/ch02/2.1"
)
// *celsiusFlag satisfies the flag.Value interface.
type celsiusFlag struct{ tempconv.Celsius }
func (f *celsiusFlag) Set(s string) error {
var unit string
var value float64
fmt.Sscanf(s, "%f%s", &value, &unit) // no error check needed
switch unit {
case "C", "°C":
f.Celsius = tempconv.Celsius(value)
return nil
case "F", "°F":
f.Celsius = tempconv.FToC(tempconv.Fahrenheit(value))
return nil
case "K", "°K":
f.Celsius = tempconv.KToC(tempconv.Kelvin(value))
return nil
}
return fmt.Errorf("invalid temperature %q", s)
}
// 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".
func CelsiusFlag(name string, value tempconv.Celsius, usage string) *tempconv.Celsius {
f := celsiusFlag{value}
flag.CommandLine.Var(&f, name, usage)
return &f.Celsius
}
var temp = CelsiusFlag("temp", 20.0, "the temperature")
func main() {
flag.Parse()
fmt.Println(*temp)
}